#pragma once
#include<cstdio>
#include<iostream>
using namespace std;
typedef int student;
//链表结构定义
struct node
{
student data;
struct node* next;
};
//链表函数声明
node CreateList(void);
node CreateNode(student);
void InsertNode(node&, student);
void PrintList(node);
//主程序
int main()
{
node head = CreateList();
student stu1 = 1;
InsertNode(head, stu1);
cout << head.next->data << endl;//可以直接打印
PrintList(head);//程序停止运行,这是为什么呢
}
//链表函数定义
node CreateList()//创建头结点
{
node head;
head.next = NULL;
return head;
}
node CreateNode(student data)//创建结点
{
node NewNode;
NewNode.data = data;
NewNode.next = NULL;
return NewNode;
}
void InsertNode(node& head, student data)//插入结点
{
node newnode = CreateNode(data);
newnode.next = head.next;
head.next = &newnode;
}
void PrintList(node Head) //打印链表
{
node* Node = new node;
Node = Head.next;
while (Node)
{
cout << "student:";
cout << Node->data << endl;
cout << endl;
Node = Node->next;
}
}
可能是你的基础不太牢固,对于堆和栈的理解不太够。我直接给你贴代码吧。
#pragma once
#include <cstdio>
#include <iostream>
using namespace std;
typedef int student;
//链表结构定义
struct node
{
student data;
struct node *next;
};
//链表函数声明
node CreateList(void);
node *CreateNode(student data);
void InsertNode(node &, student);
void PrintList(node);
//主程序
int main()
{
node head = CreateList();
student stu1 = 1;
InsertNode(head, stu1);
cout << head.next->data << endl; //可以直接打印
PrintList(head); //程序停止运行,这是为什么呢
}
//链表函数定义
node CreateList() //创建头结点
{
node head;
head.next = NULL;
return head;
}
node *CreateNode(student data) //创建结点
{
node *NewNode = new node;
NewNode->data = data;
NewNode->next = NULL;
return NewNode;
}
void InsertNode(node &head, student data) //插入结点
{
node *newnode = CreateNode(data);
newnode->next = head.next;
head.next = newnode;
}
void PrintList(node Head) //打印链表
{
node *Node = Head.next;
while (Node)
{
cout << "student:";
cout << Node->data << endl;
cout << endl;
Node = Node->next;
}
}