算法进行时--单链表(一)头尾插法
2017-02-19 22:43
183 查看
过了个新年,加上拖拖拖。距离上一篇 数据结构居然5个月了,哎
。
链表应该是当时学数据结构用得最多的了,面试的话考它的也多,它用的指针的时候也多,but 数据结构学了一年多了,差不多的都忘记了,打算开始复习一遍,毕竟靠它买面膜,哈哈。
链表第一题first:
链表中首先开始学的最多就是用头插法和尾插法:
头插法:
每次都从头开始插入结点。
运行结果:
尾插法:
正如它的它的名字一样,每次都是从尾部插和头插法刚好相反
。
链表应该是当时学数据结构用得最多的了,面试的话考它的也多,它用的指针的时候也多,but 数据结构学了一年多了,差不多的都忘记了,打算开始复习一遍,毕竟靠它买面膜,哈哈。
链表第一题first:
链表中首先开始学的最多就是用头插法和尾插法:
头插法:
每次都从头开始插入结点。
/* Instruction:Head insertion author:huangpingyi date:2017/02/19 */ #include <iostream> using namespace std; struct LNode { int data; LNode *next; }; LNode* CreateListH(LNode *L, int x, int array[]) { L->next = NULL; LNode *s;//插入的结点 int i = 0; while (i < x) { s = new LNode; s->data = array[i]; s->next = L->next; L->next = s; i++; } return L; } void Print(LNode *L) { L = L->next;//第一个是头结点 while (L != NULL) { cout << L->data << endl; L = L->next; } } int main(){ int x, array[10]; cout << "请输入插入个数:" << endl; cin >> x; cout << "输入需要插入的数据:" << endl; for (int i = 0; i < x; i++) { cin >> array[i]; } LNode* L = new LNode; CreateListH(L, x, array); cout << "用头插法的结果:" << endl; Print(L); system("pause"); return 0; }
运行结果:
尾插法:
正如它的它的名字一样,每次都是从尾部插和头插法刚好相反
/* Instruction:Tail insertion author:huangpingyi date:2017/02/19 */ #include <iostream> using namespace std; struct LNode { int data; LNode *next; }; LNode* CreateListT(LNode *L, int x, int array[]) { L->next = NULL; LNode *q = L; LNode *s;//插入的结点 int i = 0; while (i < x) { s = new LNode; s->data = array[i]; //以下三步是尾插法和头插法的区别 L->next = s; s->next = NULL; L = s; i++; } return q; } void Print(LNode *L) { L = L->next;//第一个是头结点 while (L != NULL) { cout << L->data << endl; L = L->next; } } int main(){ int x, array[10]; cout << "请输入插入个数:" << endl; cin >> x; cout << "输入需要插入的数据:" << endl; for (int i = 0; i < x; i++) { cin >> array[i]; } LNode* L = new LNode; CreateListH(L, x, array); cout << "用尾插法的结果:" << endl; Print(L); system("pause"); return 0; }运行结果:
相关文章推荐
- 算法进行时--单链表(二)常见题型01
- 【数据结构】算法5.5-5.8 广义表的头尾链表存储结构
- java小算法—判断单链表中是否有环(链表头尾不相连)
- 线性表12|循环链表 – 数据结构和算法17
- 算法训练 9-7链表数据求和操作
- Java学习之数组1(1.数组的声明;2.元素为引用数据类型的数组;3.关于main方法里的String[] args;4.数组排序;5.数3退1 数组算法,(用数组模拟链表);6数组查找之二分法;7数组的拷贝)
- 第四周项目2建设“单链表”算法库
- 第四周项目2 建设“单链表”算法库
- HNCU1326:算法2-8~2-11:链表的基本操作
- 线性链表的查找插入删除算法
- 链表之多项式计算相关算法
- 头疼的算法与数据结构——单链表详解
- 和链表有关的算法题(C++)
- 算法题目---链表中倒数第k个结点
- 算法最简单之_链表
- 给定一棵二叉树,设计一个算法,创建含有某一深度上所有结点的链表(比如:若一棵树的深度为D,则会创建出D个链表)
- iOS开发算法--链表
- 链表的倒序算法
- [算法学习]判断链表是否是环结构
- 算法习题42:修改append函数,求链表并集