链表逆置
来源:互联网 发布:申请淘宝店铺注册时间 编辑:程序博客网 时间:2024/05/17 23:24
同学提到了这个问题,自己动手编了一下。
有两种方法:递归和非递归。
递归中又有两种:带返回值的和不带返回值的。
代码如下:
/**** 链表的逆置 *****//*struct node {int a;node* next;node(): a(0), next(NULL) {}};void Creat_list(node* &head, int n){node* p = new node;p->a = n;if(!head)head->next = p;else {p->next = head->next;head->next = p;}}void show(node* &head){node* p = head->next;while(p) {cout << p->a << " ";p = p->next;}cout << endl;}//*** 非递归实现 void reverse(node* &head) //带头结点的链表反转{node* pre = head->next;node* cur = pre->next;node* nex = NULL;if(!pre || !cur)return;while(cur) {nex = cur->next;cur->next = pre;pre = cur;cur = nex;}head->next->next = NULL;head->next = pre;}//递归实现(带返回值) node* reverse(node* &head, node* cur){if(!cur || !cur->next) {head->next = cur;return cur;}else {node* tmp = reverse(head, cur->next);tmp->next = cur;cur->next = NULL;return cur;}}// 递归实现( 不 带返回值) void reverse1(node* &head, node* cur){if(!cur || !cur->next) {head->next = cur;}else {reverse(head, cur->next);cur->next->next = cur;cur->next = NULL;}}int main(){node* head = new node;Creat_list(head, 1);Creat_list(head, 2);Creat_list(head, 3);Creat_list(head, 4);Creat_list(head, 5);Creat_list(head, 6);show(head);cout << endl;//reverse(head); //非递归node* p = head->next;//node* a = reverse(head, p); // 递归带返回值 (其实不用带返回值,带返回值的较复杂)reverse1(head, p);show(head);getchar();return 0;}
0 0
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 链表逆置
- 用boost的PropertyTree json_parser 生成json字符串
- 自制电解食盐水装置
- 栈
- docker 安装 Ubuntu
- 树链剖分
- 链表逆置
- gdb 入门
- Hive 数据入库到HBase
- 《企业应用架构模式》 - 书摘精要
- 位运算
- AbsListView android:smoothScrollbar
- notifyDataSetChanged() 动态更新ListView
- Dictionary的遍历方法
- Vector用法