单链表的头插法和尾插法
来源:互联网 发布:军犬网络舆情监控系统 编辑:程序博客网 时间:2024/06/06 06:44
单链表的实现可以用数组或者指针,前者叫做顺序表示,后者叫链式表示。
链式表示常用的建表方法分头插法和尾插法,头插法的特点是输入数据的顺序与数据在链表中的存储顺序是反的,比如插入1,2,3,但是链表是3->2->1,尾插法则与头插法相反。
为了方便,单链表常被加上哨兵节点(sentinel),或者叫dummy head,哑结点。
下面是带有dummy head的头插法:
#include<stdio.h>#include<stdlib.h>typedef int DataType;#define InputSize 5struct 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 5struct 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。
运行效果:阅读全文
0 0
- 单链表的头插法和尾插法
- 单链表的头插法和尾插法
- 单链表的头插法和尾插法实现代码
- 创建单链表的头插法和尾插法
- 数据结构的 单链表的操作(头插法)和(尾插法)
- 单链表的建立(C语言):头插法和尾插法建立单链表
- 单链表的建立与删除 (使用头插法和尾插法实现)
- 头插法和尾插法建立带头节点的单链表
- 结构算法 002 单链表的头插法和尾插法
- 不带头结点的头插法和尾插法
- l链表的头插法和尾插法
- 数据结构,头插法和尾插法的关键代码
- 头插法和尾插法创建单链表
- 头插法和尾插法创建单链表
- 数据结构学习(二)——单链表的操作之头插法和尾插法创建链表
- C/C++学习(七)单链表的头插法,尾插法,元素插入、删除和查找 .
- 头插法(逆序)和尾插法(顺序)实现单链表的创建与排序
- 数据结构学习(二)——单链表的操作之头插法和尾插法创建链表
- Apache Tomcat版本各版本
- jvm系列(二):JVM内存结构
- 【HDU】4857--逃生(拓扑)
- EasyDSS流媒体解决方案之Grunt的使用简介
- js语句switch的一个小案例
- 单链表的头插法和尾插法
- Sublime 的安装及使用
- C#设计模式(十)观察者模式(Observer Pattern)
- c++的编译环境
- 集合和泛型
- Linux下创建用于并指定该用户的主目录和相关权限
- 用Bootstrap栅格系统表单
- Java循环控制
- JVM笔记(一)