【数据结构】递归实现链表逆序
发布时间:2020-12-15 06:32:56 所属栏目:安全 来源:网络整理
导读:关于本篇文章,先参见本人之前的一篇博客,与之相关: http://blog.csdn.net/kuzuozhou/article/details/7451289 另外,参考: http://blog.csdn.net/ssjhust123/article/details/7754103 #includestdio.h #include stdlib.htypedef struct node//节点存放一
关于本篇文章,先参见本人之前的一篇博客,与之相关: http://blog.csdn.net/kuzuozhou/article/details/7451289 另外,参考: http://blog.csdn.net/ssjhust123/article/details/7754103 #include<stdio.h> #include <stdlib.h> typedef struct node//节点存放一个数据和指向下一个节点的指针 { int data; struct node* pnext; } Node; Node *link_create()//链表创建 { int item; Node *head = NULL; do { Node *p; scanf("%d",&item); p = (Node *)malloc(sizeof(Node)); if(p == NULL) { printf("memory applied failedn"); break; } p->data = item; p->pnext = head; head = p; }while(getchar() != 'n'); return head; } void link_show(Node *head) { Node* p; p=head; while(p != NULL) { printf("%d ",p->data); p = p->pnext; } printf("n"); } void link_destroy(Node *head) { Node* p; Node* tmp; p=head; while(p != NULL) { tmp = p->pnext; free(p); p = tmp; } } //Node *link_reverse(Node *head) //{ // Node *pre,*cur,*next; // /*head->pnext =NULL;*/ // // pre = head; // cur = pre->pnext; // next = cur->pnext; // head->pnext =NULL;//第一次的pre,cur,next // // if(next == NULL)//链表只有两个节点,如果没有此语句,当链表确实只有两个节点时,就会发生错误。 // { // cur->pnext = pre; // head = cur; // return head; // } // // while(next->pnext != NULL) // { // cur->pnext = pre;//修改指针,每次循环修改一次 // // pre = cur; // cur = next; // next = next->pnext; // }//循环终止时,next->pnext == NULL // cur->pnext = pre; // next->pnext = cur; // head = next; // return head; // //} void link_reverse(Node **headRef)//递归来实现链表逆序,相比上面注释的部分实现,显得相当简洁 { Node *first,*rest; if(*headRef == NULL) return; first = *headRef; rest = first->pnext; if(rest == NULL) return; link_reverse(&rest); first->pnext->pnext = first; first->pnext = NULL; *headRef = rest; } int main() { Node *new_head=NULL; Node *head = link_create(); link_show(head); //new_head = link_reverse(head); link_reverse(&head); link_show(new_head); link_destroy(new_head); //system("pause"); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |