#include<iostream>
using namespace std;
typedef struct Node {
int data; //储存节点数据
struct Node* next; //指向下一个节点的指针
} List;
List *MakeEmpty() { //创建一个空的链式表
List *head; //定义头指针
head = (List*)malloc(sizeof(struct Node)); //申请空间
head->next = NULL; //头指针指向的头节点为空
return head;
}
bool Charge(List* L) { //判断链式表是否为空
if (L->next == NULL)
return true;
else
return false;
}
List *Add(List* L,int n) { //这个函数是往这个链表里填数据
List* head=NULL, * p=NULL, * tail=NULL; //定义出头节点,操作节点,和尾节点
int i = 1;
while (n--) {
p = (List*)malloc(sizeof(struct Node));
printf("请输入第%d个数:", i);
cin >> p->data;
p->next = NULL;
if (head == NULL)
head = p;
else
tail->next = p;
tail = p;
i++;
}
return head;
}
void Print(List* L) {
while (L) {
cout << L->data << " ";
L = L->next;
}
}
int main() {
List* L = MakeEmpty();
cout << "链表是否是空的?" << endl;
if (Charge(L))
cout << "是" << endl;
else
cout << "不是" << endl;
cout << "请输入链表的长度:";
int n;
cin >> n;
cout << endl;
L=Add(L, n); //这个地方试了好多次,都忘了把返回值赋给L
cout << "所得链表:";
Print(L);
}