头插法和尾插法建立带头节点的单链表
2016-04-12 11:49
267 查看
有两种方法建立单链表,尾插法和头插法,他们的区别是:头插法是按照输入元素倒序建立,为尾插法为顺序插入,并且多一个尾节点,我们一般使用尾插法。
一.头插法
代码为:
二.尾插法
完整代码如下:
一.头插法
代码为:
pCurr -> next = pHead -> next; pHead -> next = pCurr;
二.尾插法
pTail -> next = pCurr; pTail = pCurr;
完整代码如下:
//头插法和尾插法建立单链表及
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
Node* next;
};
void tailInvert(int* data);
void headInvert(int* data);
int main() {
int data[5] = {1, 2, 3, 4, 5};
tailInvert(data);
printf("\n");
headInvert(data);
}
void tailInvert(int* data) {
Node* pHead = (Node*)malloc(sizeof(Node));
Node* pCurr = NULL;
Node* pTail = pHead;
for(int i = 0; i < 5; ++i) {
pCurr = (Node*)malloc(sizeof(Node));
pCurr -> data = data[i];
pTail -> next = pCurr; pTail = pCurr;
}
pTail -> next = NULL;
printf("尾插法:\n");
for(int j = 0; j < 5; ++j) {
printf("%d\t", pHead -> next -> data);
pHead = pHead -> next;
}
}
void headInvert(int* data)
{
Node* pHead = (Node*)malloc(sizeof(Node));
pHead -> next = NULL;
Node* pCurr = NULL;
for(int i = 0; i < 5; ++i) {
pCurr = (Node*)malloc(sizeof(Node));
pCurr -> next = pHead -> next; //巧妙
pCurr -> data = data[i];
pHead ->next = pCurr;
}
printf("头插法:\n");
for(int j = 0; j < 5; ++j) {
printf("%d\t", pHead -> next -> data);
pHead = pHead -> next;
}
}
相关文章推荐
- 中文信息处理 N-gram模型
- 解决无法使用 windows ssh 远程登录 Ubuntu 的问题
- PopWindow分享到第三方app的弹出窗口
- PXE网络装机(有人值守与无人值守安装)
- 存储过程中创建临时表,为何没有权限?
- 索引i - 1 数据的获取, 与索引i数据 同时获取
- 退出Activity时AsynTask的处理
- RA layer request failed
- MySQL数据库——常用操作命令
- 手把手教会popupWindow从下往上弹出效果的实现
- PHP递归生成树形数组
- eclipse中的web-inf下没有web.xml
- mysql主键自增长获取
- PHP中Restful api 错误提示返回值实现思路
- Xjad配置
- notepad 删除^M
- Redis实现分布式锁
- 法线从object space到eye space的转换((normal matrix)
- GPU Analyzer 神器:Intel INDE
- 外部类内部类之间调用的demo