用递归方法反转链表的问题
尝试用迭代和递归两种方法实现链表反转。全部代码如下。 迭代方法void iterative_reverse() 经测试没有问题,
但递归方法 mylist* recursive_reverse(mylist* root)
一运行就死循环,不知道问题在哪里,求高手指教~
谢谢
程序代码:
#include<stdio.h> #include<stdlib.h> typedef struct list { int node; struct list *next; }mylist; mylist *head; mylist* create_node(int node_number) { mylist *p; p = (mylist*)malloc(sizeof(mylist)); if (p == NULL) { printf("No enough memory!"); } p->node = 10*node_number; p->next = NULL; printf("\nA new node created."); return p; } void disp_list(mylist *head) { mylist *p; int j=0; p=head; do{ printf("\n%5d%10d", j,p->node); j++; p=p->next; }while(p!=NULL); } void iterative_reverse() { mylist *p, *q, *r; p = head; q = p-> next; p->next = NULL; while(q!= NULL) { r = q->next; q->next = p; p = q; q = r; } head = p; } mylist* recursive_reverse(mylist* root) // 本函数有问题 { if(root->next!=NULL) { recursive_reverse(root->next); root->next->next=root; return root; } else { head = root; return root; } } main() { int i = 0; mylist *pr; char ctrl; while(1) { printf("\nPress 'i' to insert one new node!"); ctrl=getch(); if(ctrl!='q'&&ctrl!='i') continue; if(ctrl=='q') break; if(i==0) { head=create_node(i); pr=head; } else { pr->next=create_node(i); pr=pr->next; } i++; } disp_list(head); iterative_reverse(); printf("\nAfter Reverse"); disp_list(head); head = recursive_reverse(head); printf("\nAfter 2nd Reverse"); disp_list(head); system("pause"); }
[ 本帖最后由 neverlandzzy 于 2011-4-4 10:56 编辑 ]