单链表的头插法和尾插法

单链表的实现可以用数组或者指针,前者叫做顺序表示,后者叫链式表示。

链式表示常用的建表方法分头插法和尾插法,头插法的特点是输入数据的顺序与数据在链表中的存储顺序是反的,比如插入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。

运行效果:



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值