链表逆置

来源:互联网 发布:申请淘宝店铺注册时间 编辑:程序博客网 时间: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
原创粉丝点击