C语言反转单链表
2016-06-15 15:24
323 查看
1、反转单链表
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。链表结点定义如下:
struct node //结点类型定义
{
int val; //结点的数据域
struct node *pNext;//结点的指针域(存放结点的直接后继的地址)
};
2、链表的结点结构
┌───┬───┐
│data
│next │
└───┴───┘
data域 -- 存放结点值的数据域
next域 -- 存放结点的直接后继的地址(位置)的指针域(链域)
[cpp]
view plain
copy
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node *pNext;
};
struct node *gen()
{
struct node *pHead = NULL;
printf("反转前::");
for(int i = 10; i > 0; i--){
// 创建了一个空节点并分配内存,此时此节点还没有数据,为空节点
struct node * p = (struct node *)malloc(sizeof(struct node));
//在空节点的data域赋值
p -> val = i;
//因为pHead初始化时为NULL,第一次for循环表示是第一个节点(后面无其他节点),p->pNext的下个节点为NULL空
p -> pNext = pHead;
//将已填充好的第一次分配的节点p赋值给pHead,此时pHead不为空,以此循环翻转链表
pHead = p;
printf("%d ",i);
}
printf("\n");
return pHead;
}
void display(struct node *pHead)
{
printf("反转后::");
while( pHead != NULL)
{
printf("%d ", pHead->val);
pHead = pHead->pNext;
}
printf("\n");
}
//递归实现
struct node * reverse(struct node *pHead)
{
if (pHead == NULL || pHead -> pNext == NULL)
{
return pHead;
}
struct node *p = pHead -> pNext;
struct node *pNewHead = reverse(p);
p -> pNext = pHead;
pHead ->pNext = NULL;
return pNewHead;
}
//尾递归实现
struct node * do_reverse_tail(struct node *pHead, struct node *pNewHead)
{
if(pHead == NULL)
{
return pNewHead;
}
else
{
struct node *pNext = pHead->pNext;
pHead->pNext = pNewHead;
return do_reverse_tail(pNext, pHead);
}
}
struct node * reverse_tail(struct node *pHead)
{
return do_reverse_tail(pHead, NULL);
}
//迭代实现
struct node * reverse_it(struct node *pHead)
{
struct node *pNewHead = NULL;
struct node *pPrev = NULL;
struct node *pCur = pHead;
while(pCur != NULL)
{
struct node *pTmp = pCur->pNext;
if(pTmp == NULL)
{
pNewHead = pCur;
}
pCur->pNext = pPrev;
pPrev = pCur;
pCur = pTmp;
}
return pNewHead;
}
int main()
{
struct node *pHead = gen();
display(pHead);
pHead = reverse_it(pHead);
display(pHead);
}
相关文章推荐
- HDOJ 2011 多项式求和
- C++primer函数引用形参 左值和右值d额
- C++实践参考——人数不定的工资类
- VC中遍历文件夹下的文档及子文件夹
- C++ 的explicit 关键字
- c语言中冒泡排序、插入排序、选择排序算法比较
- [leetcode] 【字符串】 12. Integer to Roman
- C语言程序报告
- c++ STL学习之stack堆栈总结
- C++实践题:我的数组类
- C++程序设计语言练习7.8 二维数组操作
- C++—文件操作
- C语言打印当前时间
- loki 练习
- C语言宏定义##连接符和#符的使用
- C++中函数的返回值
- C++中explicit关键字的作用
- C++信号处理
- C++第三次作业
- LeetCode349. Intersection of Two Arrays我的做法