下面是源码,好累,明天再慢慢分析。
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
using namespace std;
struct node{
int data; node *next;
};
node *Create(node *head, intn);
void print(node *h);
int main()
{
node *list;
list = NULL;
int n;
cout << "请输入链表的长度:" <<endl;
cin >> n;
list = Create(list, n);
print(list);
}
node *Create(node *head, intn)
{
node *last, *p =NULL;
head =(node*)malloc(sizeof(node));//建立为表头结点
head->next =NULL;//将next域置空
last = head;//last为指向尾节点的指针此时完成last与head的连接
for (int i = 0; i < n; i++)
{
p =(node*)malloc(sizeof(node));//为下一个结点申请内存空间
//p->next = NULL;
cin >>p->data;//输入到他的data
last->next =p;//将下一结点的地址赋值给last的next 完成last与p的连接 此时head与last一同指向p
last = p;//将p赋值给last即为下一次循环做准备
//p = p->next;
p->next = NULL;//不要忘记制空
}
return head;
}
void print(node *head)
{
const node *p;
p = head;
p = p->next;
while (p != NULL)
{
cout << p->data << "";
p = p->next;
}
cout << endl;
}