单链表就地反转
反转 单链
2023-09-14 08:58:00 时间
实现一个函数:void reverse(struct list_node *head)在尽量不借助辅助变量的情况下,实现任意长度单链表(不考虑内存限制)的反转(or 逆序)。
struct list_node{ int val; struct list_node *next; struct list{ struct list_node *head; struct list_node *tail; void reverse(struct list_node *head) int main() struct list list = {NULL, NULL}; struct list_node *p = NULL; /*init list*/ /*打印反转前各节点的值*/ reverse(list.head); p = list.head; list.head = list.tail; list.tail = p; /*打印反转后各节点的值*/ }代码实现:
#include stdio.h struct list_node{ int index; struct list_node *next; struct list struct list_node *head; struct list_node *tail; void reverse(struct list_node *head) if(NULL == head|| NULL == head- next ) return; reverse(head- next); head- next- next = head; head- next = NULL; int main() int i = 0; struct list list = {NULL, NULL}; struct list_node node[10] = {0}; struct list_node *p; for(i = 0; i i++) node[i].index = i; node[i].next = node[i + 1]; node[9].index = 9; list.head = node; list.tail = node + 9; reverse(list.head); for(p = list.tail; p; p=p- next) printf("%d \n",p- index); return 0; }
链表——单链表的反转 单链表的反转就是从原链表的第一个存 数据的结点开始,依次递归调用反转每一个结点,直到把最后一个结点反转完毕
相关文章
- Java面向对象高级--继承的应用----整形数组类、排序类、反转类
- Java实现 LeetCode 344 反转字符串
- Java实现 LeetCode 7整数反转
- (Java实现) 洛谷 P1553 数字反转(升级版)
- (Java实现) 洛谷 P1553 数字反转(升级版)
- [LeetCode] Reverse Linked List(递归与非递归反转链表)
- 206. 反转链表
- android 算法题(顺时针打印矩阵,数字字符串反转输出 ,阶乘)
- 【MATLAB】信号的平移、反转和尺度变换
- python单链表反转
- 1.4Spring 依赖注入(DI)和控制反转(IOC)详解
- 反转链表
- 【LeetCode】剑指 Offer II 024. 反转链表