【資料結構】遞迴實現連結串列逆序

pengfoo發表於2012-10-01

關於本篇文章,先參見本人之前的一篇部落格,與之相關:

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 failed\n");
			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;
}


相關文章