了解链表,要知道它是一种数据结构。如果数据结构不会的话不用学整本数据结构,只学引论就可以了。(但至少数据,数据元素,数据项得达到能背会到能用自己的话说出来,至少沉淀个2,3天吧)。
链表和指针密切相关。而指针真正理解到哪一步算会呢?理解到指针的类型、指针所指向的类型、指针的值即指针所指向的内存区、还有指针本身所占据的内存区的程度就可以了。
next->需要一个结构体。
结构体是什么,就像java中的一个类。里面有字段。然后把节点这个概念抽象出来,做成结构体,然后用&一串,就可以组成一个链表。针对自己的链表还需要完善增删改查等操作。网上有更详细的操作步骤表,这里就不列举了。好了,代码献上。
#include <iostream>
using namespace std;
void Init_List();
//定义了一个结点模型,这里面有两个元素,一个是每个结点的数据,一个是每个结点模型的必要指针用以存放下一个结点的地址。
struct node{
int data;
struct node *next;
};
//生明了一个结点。
typedef struct node mylist;
void main()
{
//Init_List();
//给这个结点放一个头指针
struct node *head=NULL;
head=(mylist *)malloc(sizeof(mylist));
if(head==NULL)
{
cout<<"malloc fair"<<endl;
}
struct node n1;
head=&n1;
n1.data=NULL;
n1.next=NULL;
struct node n2,*p,n3,n4,n5; // n1 n2
p=head;
n2.data=2;
n3.data=3;
n4.data=4;
n5.data=5;
n1.next=&n2;
n2.next=&n3;
n3.next=&n4;
n4.next=&n5;
n5.next=NULL;
struct node n6;
n6.data=6;
n6.next=NULL;
cout<<p->data<<endl<<endl;
while(!(p->next==NULL))
{
p=p->next;
}
p->next=&n6;
p = head;
while(!(p->next==NULL))
{
p=p->next;
cout<<p->data<<endl;
}
}
void Init_List()
{
//给这个结点放一个头指针
struct node *head=NULL;
struct node *p=head;
head=(mylist *)malloc(sizeof(mylist));
if(head==NULL)
{
cout<<"malloc fair"<<endl;
}
struct node n1;
head=&n1;
n1.data=1;
n1.next=NULL;
free(head);
}