单链表的逆置操1
来源:互联网 发布:网络割接流程 编辑:程序博客网 时间:2024/06/06 18:58
头结点有数据的单链表
方法1:
LinkList reverse_list(LinkList list)
{
LinkedNode *pre = list;
LinkedNode *cur = list->next;
LinkedNode *next = NULL;
if(list == NULL || list->next == NULL)
return;
/*在这里实现翻转*/
while(cur != NULL)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
list->next = NULL;
list = pre;
return list;
}
方法2:递归
void reverse_the_list(LinkedNode *cur, LinkList *list)
{
LinkedNode *next = NULL;
if(cur == NULL || cur->next == NULL)
{
*list = cur;
}
else
{
next = cur->next;
reverse_the_list(next, list);
next->next = cur;
cur->next = NULL;
}
return;
}
完整代码:
#include <stdio.h>
#include <malloc.h>
typedef int DataType;
typedef struct node
{
DataType data;
struct node *next;
}LinkedNode, *LinkList;
LinkList create_list()
{
DataType value[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(value) / sizeof(DataType);
int i = 0;
LinkedNode *list_head = NULL;
LinkedNode *temp = NULL;
LinkedNode *p = NULL;
list_head = (LinkedNode*)malloc(sizeof(LinkedNode));
list_head->data = value[0];
list_head->next = NULL;
temp = list_head;
for(i = 1; i < len; i++)
{
while (temp->next != NULL)
{
temp = temp->next;
}
p = (LinkedNode*)malloc(sizeof(LinkedNode));
p->data = value[i];
p->next = NULL;
temp->next = p;
}
return list_head;
}
void print(LinkList list)
{
LinkedNode *temp = NULL;
if(list == NULL)
return;
temp = list;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
return;
}
LinkList reverse_list(LinkList list)
{
LinkedNode *pre = list;
LinkedNode *cur = list->next;
LinkedNode *next = NULL;
if(list == NULL || list->next == NULL)
return;
/*在这里实现翻转*/
while(cur != NULL)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
list->next = NULL;
list = pre;
return list;
}
void reverse_the_list(LinkedNode *cur, LinkList *list)
{
LinkedNode *next = NULL;
if(cur == NULL || cur->next == NULL)
{
*list = cur;
}
else
{
next = cur->next;
reverse_the_list(next, list);
next->next = cur;
cur->next = NULL;
}
return;
}
int main()
{
LinkList list = NULL;
LinkedNode *temp = NULL;
LinkedNode *temp1 = NULL;
list = create_list();
print(list);
printf("after first reverse:the node is:\n");
temp=reverse_list(list);
print(temp);
temp1 = temp;
reverse_the_list(temp1, &temp);
printf("after second reverse:the node is:\n");
print(temp);
return 0;
}
实验结果:
- 单链表的逆置操1
- 单链表的归并1
- 单链表的参考1
- 单链表的实现类1
- 在 O(1) 的时间内删除单链表的结点
- 第四周项目(1)-单链表的的建立
- 单链表的C++的实现
- 单链表的9的操作
- 数据结构1-简单单链表的创建
- 数据结构--单链表“环”的问题(1)
- 实战数据结构(1)_单链表的操作
- 项目3 -- 单链表的应用(1)
- 项目3 -- 单链表的应用(1) .
- Data Structure(1-4)---单链表的读取
- 单链表的应用1(去重)
- 【面试题】单链表的操作1
- 第四周 单链表的应用(1)
- 数据结构基础:单链表的应用(1)
- Navicat 中文破解版安装
- ZOJ 2112-Dynamic Rankings (树状数组+主席树)
- NYOJ题目325-zb的生日
- idea工具的个人配置
- Oracle数据库和实例
- 单链表的逆置操1
- POJ2562 UVA10035 ZOJ1874 Primary Arithmetic【进制+进位】
- 完全二叉树计数
- Cpage.js给组件绑定事件
- ARM体系结构要点
- VMware Network Adapter VMnet1/8详解
- poj1348求凸包周长
- CodeForces
- 用Win32,写一个自定义的定时器