相当于整个链表是依靠指针串联起来的。
需要注意每一个结点也是一个指针,每个结点(即结构)里还有一个指针。
--node.h--
#ifndef _NODE_H_
#define _NODE_H_
typedef struct node{
int value;
struct node *next;
}node;
#endif
--node.c--
#include <stdio.h>
#include "node.h"
//typedef struct node{
// int value;
// struct node* next;
//}node;
int main(int argc,char const *argv[]){
int number=0;
while(number!=-1)
{
scanf("%d",&number);
if (number!=-1)
{
node* head=NULL;
node* p=(node*)malloc(sizeof(node));
p->value=number;
p->next=NULL;
node* last=head;
if (last!=NULL)
{
while (last->next!=NULL)
{
last=last->next;
}
last->next=p;
}else
{
head=p;
}
}
}
return 0;
}
创建链表过程中的过程可以简述为:如果发现头指针指向NULL,也就是链表此时为空,没有一个结点,那就让头指针指向这个结点;如果发现头指针已经指向一个结点了,即链表不为空,那么就通过遍历找到最后那个结点,让最后那个结点指向新创建的那个结点,也就是每次新创建的结点都在最后。
还有一个值得疑惑的点就是每次创建的新结点我们都是node* p=(node*)malloc(sizeof(node));这句话的含义并不是每次都定义一个node*型的变量p,而是以p的名号每次申请一块内存,第一次申请内存后,并没有释放就又重新申请,但因为我们将每块内存都串起来了,所以并不会出现我们讲过的内存泄露问题,(内存泄漏(Memory Leak):程序和内存失去了联系,再也无法对它进行任何操作),因为我们有办法联系到那块内存,这也就是链表的强大功能之一。
上述方法每次创建的结点都在末尾,即尾指针创建链表,自然也就有头指针创建链表。
即每次创建的结点都在第一个。所以如果要输出每个结点只有倒序输出,所以可以视情况自由选择。
--main.h--
#ifndef _MAIN_H_
#define _MAIN_H_
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int value;
struct node *next;
}node;
#endif
--main.c--
#include <stdio.h>
#include "main.h"
//typedef struct node{
// int value;
// struct node* next;
//}node;
int main(int argc,char const *argv[]){
int number=0;
node* head=NULL;
while(number!=-1)
{
scanf("%d",&number);
if (number!=-1)
{
node* p=(node*)malloc(sizeof(node));
p->value=number;
p->next=NULL;
if (head==NULL)
{
head=p;
}
else
{
p->next=head;
head=p;
}
}
}
node *last=head;
while (last!=NULL)
{
printf("%d ",last->value);
last=last->next;
}
return 0;
}
1 2 3 4 5 6
-1
6 5 4 3 2 1
--------------------------------
Process exited after 5.681 seconds with return value 0
请按任意键继续. . .