#include <stdio.h>
struct Node{
int data;
Node *next;
public:
Node()
{
Node(0,NULL);
}
Node(int data)
{
Node(data,NULL);
}
Node(int data,Node *next)
{
this->data=data;
this->next=next;
}
};
Node* CreList(int size)
{
Node* p;
Node* pPre;
for (int i=0;i<size;i++)
{
pPre=p;
p=new Node(size-i,(i==0)?NULL:pPre);
}
return p;
}
void Print(Node* p)
{
while (p!=NULL)
{
printf("%d,",p->data);
p=p->next;
}
printf("\n");
}
Node* RevList_Bak(Node *head , Node* pre)//C面试算法解析
{//递归实现单链表的逆转
Node* p = head->next;//数据位置不动,单纯改变指针的指向,方向
head->next = pre;
pre = head;
if(p) return RevList_Bak(p,pre);
else return head;
}
Node* RevList(Node *head,Node *pPrev )
{
Node * pNext;
if (head->next!=NULL)
{
pNext=head->next;
head->next=pPrev;
return RevList(pNext,head);
}
else
{
head->next=pPrev;
return head;
}
}
void main(int argc,char* argv[])
{
Node*p = CreList(6);
Print(p);
Node* q = RevList(p,NULL);
Print(q);
}
/*
1,2,3,4,5,6,
6,5,4,3,2,1,
Press any key to continue
*/
//递归
Node* RevList(Node *head,Node *pPrev )
{
Node * pNext;
if (head->next!=NULL)
{
pNext=head->next;
head->next=pPrev;
return RevList(pNext,head);
}
else
{
head->next=pPrev;
return head;
}
}
//循环
Node* RevList(Node *head )
{
Node * pNewList=NULL;
Node *pOldList=head;
while (pOldList->next!=NULL)
{
Node * pOldListNext=pOldList->next;
pOldList->next=pNewList;
pNewList=pOldList;
pOldList=pOldListNext;
}
pOldList->next=pNewList;
pNewList=pOldList;
return pNewList;
}
void main(int argc,char* argv[])
{
Node*p = CreList(6);
Print(p);
//Node* q = RevList(p,NULL);
Node* q = RevList(p);
Print(q);
}
/*
1,2,3,4,5,6,
6,5,4,3,2,1,
Press any key to continue
*/