單鏈表逆置問題:
1頭插法
2遞歸
具體過程大致圖如下:
代碼實現:
#include <iostream>
using namespace std;
typedef int elemtype;
typedef struct ListNode
{
elemtype data;
ListNode *next;
}ListNode,*List;
ListNode *Buynode()
{
ListNode* p = (ListNode *)malloc(sizeof(ListNode));
if (NULL == p)
exit (-1);
memset(p,0,sizeof(ListNode));
p->next = NULL;
return p;
}
ListNode *init_list()
{
ListNode *p = Buynode();
return p;
}
void push_front(ListNode *head,int value)
{
if (head == NULL)
{
return;
}
ListNode*p = Buynode();
p->data = value;
p->next = head->next;
head->next = p;
}
void print(ListNode *head)
{
if (head == NULL)
return ;
ListNode *pcur = head->next;
while (pcur != NULL)
{
cout<<pcur->data<<" ";
pcur = pcur->next;
}
cout<<endl;
}
////////////鏈表逆置--頭插法////////////////////
void rerverse(ListNode *head)
{
if (head == NULL)
return ;
ListNode *p = head->next;
ListNode *s = NULL;
head->next = NULL;
while (p!= NULL)//頭插s,改變頭結點的指向
{
s = p;
p = p->next;
s->next = head->next;
head->next = s;
}
}
////////////////////////鏈表逆置 (遞歸)//////////////////////////
ListNode *phead = NULL;//用來記錄逆置之後新的第一個結點
void reverse2(ListNode *s,ListNode *p)
{
if (p != NULL)
{
reverse2(p,p->next);
p->next = s;//返回的時候指針反向
}
else
{
phead = s;//記錄新的第一個結點
}
}
void reverse1(ListNode *head)
{
if (head == NULL)
return;
ListNode *p = head->next;//注意遞歸的起始條件
ListNode *s = NULL;
reverse2(s,p);
}
void main()
{
List head;
int ar[] = {12,23,34,45,56,67,78,89,90,100};
int len = sizeof(ar)/sizeof(ar[0]);
head= init_list();
for (int i = 0;i<len;++i)
{
push_front(head,ar[i]);
}
print(head);
reverse1(head);
head->next = phead;
print(head);
}