定义:链表由节点组成,每个节点都有一个数据value和一个指针。
注意:我一开始写的代码都是有问题的代码,我是一步步分析翁恺老师的代码如何从不完整走向完整的过程。
typedef struct node_{
int value;
struct node_ *next;
} Node;
定义了节点的结构,一个value一个指针next;
图1-1
我们要在这个链表后面加入一个节点的话,每次我们都需要初始化一个节点。
以下的代码,是head节点不为NULL 的情况!! 上面的这个图主要是为了,更好的让大家理解新增的节点如何初始化,下面是翁恺老师上课的代码示例。
#include<stdio.h>
#include<stdlib.h>
typedef struct node_{
int value;
struct node_ *next;
}Node;
int main(){
int number;
do {
//初始化新增的节点
scanf("%d",&number);
if(number != -1){
Node *p= (Node *)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
}
}while(number != -1);
return 0;
}
对于新增的节点,它需要分配一个Node一样大的空间,让它存放value和next指针,同时next要是NULL。
在加入一个新增节点前,我们需要找到原来链表的最后节点。这个最后节点有个特点(不明白这句话可以看图1-1),它的指针=null。利用这个我们可以写遍历,从head节点开始,while(last->next),当last不是NULL的时候,会一直循环。
#include<stdio.h>
#include<stdlib.h>
typedef struct node_{
int value;
struct node_ *next;
}Node;
int main(){
int number;
do {
scanf("%d",&number);
if(number != -1){
Node *p= (Node *)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//find the last node
Node *last=head; // head是一个node的指针类型,我们定义一个last指针和它做赋值运算。
while(last->next){
last = last->next;
}
//走出这个循环,意味着last=null,已经走到最后的节点了。
last->next=p;
}
}while(number != -1);
return 0;
}
写到这里还是有一个问题的,我们这个代码我们这个last能循环的原因在于我们的head不是NULL,我们这个链表linked-list是有头节点的。可是当我们的HEAD节点不存在,是NULL的情况呢?
一个完整的对链表的初始化的一个代码应该是如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct node_{
int value;
struct node_ *next;
}Node;
int main(){
Node *head=NULL;
int number;
do {
scanf("%d",&number);
if(number != -1){
Node *p= (Node *)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//find the last node
Node *last=head; // head是一个指针类型,我们定义一个last指针和它做赋值运算。
//赋值运算之后做判断,链表的头节点存在不存在。
if(last){
while(last->next){
last = last->next;
}
//走出这个循环,意味着last=null,已经走到最后的节点了。
last->next=p;
}else
{
head=p;
}
}
}while(number != -1);
return 0;
}
我们要考虑一开始无数据的情况,所以有Node *head=null;
在后面的时候会进行判断,如果last无法进行遍历循环,我们就让head节点为新增节点。