单链表的实现可以用数组或者指针,前者叫做顺序表示,后者叫链式表示。
链式表示常用的建表方法分头插法和尾插法,头插法的特点是输入数据的顺序与数据在链表中的存储顺序是反的,比如插入1,2,3,但是链表是3->2->1,尾插法则与头插法相反。
为了方便,单链表常被加上哨兵节点(sentinel),或者叫dummy head,哑结点。
下面是带有dummy head的头插法:
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
#define InputSize 5
struct Node{
DataType dt;
struct Node* next;
};
int main(){
struct Node* head=(struct Node*)malloc(sizeof(struct Node));
struct Node* for_print;
head->dt=INT_MIN;
head->next=NULL;
for(int i=0;i<InputSize;i++){
DataType num;
struct Node* tmp=(struct Node*)malloc(sizeof(struct Node));
scanf("%d",&num);
tmp->dt=num;
tmp->next=head->next;
head->next=tmp;
}
//print:
printf("the list is:\n");
for_print=head->next;
while(for_print){
printf("%d ",for_print->dt);
for_print=for_print->next;
}
return 0;
}
运行效果:
下面是带有dummy head的尾插法:
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
#define InputSize 5
struct Node{
DataType dt;
struct Node* next;
};
int main(){
struct Node* head=(struct Node*)malloc(sizeof(struct Node));
struct Node* helper=(struct Node*)malloc(sizeof(struct Node));
struct Node* for_print;
head->dt=INT_MIN;
head->next=NULL;
helper=head;
for(int i=0;i<InputSize;i++){
DataType num;
struct Node* tmp=(struct Node*)malloc(sizeof(struct Node));
scanf("%d",&num);
tmp->dt=num;
tmp->next=NULL;
helper->next=tmp;
helper=helper->next;
}
//print:
printf("the list is:\n");
for_print=head->next;
while(for_print){
printf("%d ",for_print->dt);
for_print=for_print->next;
}
return 0;
}
可见,尾插法需要一个辅助指针helper。
运行效果: