#include <iostream>
#include <stdio.h>
using namespace std;
struct ListNode
{
ListNode* p_Next;
int p_Value;
};
ListNode* Reverse_List(ListNode* pHead)
{
//非递归实现单链表逆序输出。
ListNode* pHead_New = NULL;
ListNode* pTemp = pHead;
ListNode* pAfter = NULL;
ListNode* pPre = NULL;
//第一种写法:
while(pHead!= NULL)
{
pAfter = pHead->p_Next;
pHead->p_Next = pPre;
pPre = pHead;
pHead = pAfter;
//pAfter = pAfter->p_Next;//多此一举
}
pHead = pPre;
return pHead;
//第二种写法:
/*
while(pTemp != NULL)
{
pAfter = pTemp->p_Next; //save the next Node
if(pAfter == NULL)
pHead_New = pTemp;
pTemp->p_Next = pPre;
pPre = pTemp;
pTemp = pAfter;
}
return pHead_New;
*/
}
ListNode* Reverse_List_recurrence(ListNode* pHead)
{
//递归调用实现单链表逆序。
//ListNode* new_head = pHead;
if(pHead == NULL || pHead->p_Next == NULL) //空或者只有一个节点
return pHead;
else
{
ListNode* new_Head = Reverse_List_recurrence(pHead->p_Next);
pHead->p_Next->p_Next = pHead;
pHead->p_Next = NULL;
return new_Head;
}
}
int main()
{
//Test case! //simple test
ListNode a,b,c,d;
a.p_Value = 1, a.p_Next = &b;
b.p_Value = 2, b.p_Next = &c;
c.p_Value = 3, c.p_Next = &d;
d.p_Value = 4, d.p_Next = NULL;
/*
a->p_Value = 1, a->p_Next = b;
b->p_Value = 2, b->p_Next = c;
c->p_Value = 3, c->p_Next = d;
d->p_Value = 4, d->p_Next = NULL;
*/
ListNode* pHead = &a;
printf("%d %d\n", pHead->p_Value,pHead->p_Next->p_Value);
printf("%d %d %d %d \n",a.p_Value ,b.p_Value, c.p_Value, d.p_Value);
ListNode* p = Reverse_List_recurrence(pHead);
printf("%d %d\n", p->p_Value,p->p_Next->p_Value);
printf("%d %d %d %d \n",a.p_Value ,b.p_Value, c.p_Value, d.p_Value);
}
程序员面试宝典之数据结构基础---⑤单链表逆序的递归与非递归实现
最新推荐文章于 2024-08-25 20:38:11 发布