两种方法:
1. 借助栈操作,先入栈,然后再出栈形成新的链表;
2. 原地逆序。
#include <iostream>
#include <stack>
using namespace std;
struct LinkNode{
int m_nValue;
LinkNode* next;
};
typedef LinkNode* LinkList;
void InsertList(LinkList &list, int data)
{
LinkList head=list;
LinkList p=list;
LinkList q;
if(head==NULL)
{
head=new LinkNode;
head->m_nValue=data;
head->next=NULL;
list=head;
}
else
{
while(p->next)
p=p->next;
q=new LinkNode;
q->m_nValue=data;
q->next=NULL;
p->next=q;
}
}
//借助栈操作
void reverse1(LinkList &list)
{
stack<LinkList> s;
LinkList p=list;
LinkList q=NULL,r;
while(p)
{
s.push(p);
p=p->next;
}
while(!s.empty())
{
if(q==NULL)
{
q=s.top();
s.pop();
q->next=NULL;
list=q;
r=list;
}
else
{
q=s.top();
s.pop();
r->next=q;
q->next=NULL;
r=q;
}
}
}
//原地逆序
void reverse2(LinkList &list)
{
LinkList p=list,q;
list=NULL;
while(p)
{
q=p->next;
p->next=list;
list=p;
p=q;
}
}
void PrintList(LinkList list)
{
LinkList p=list;
while(p)
{
cout<<p->m_nValue<<" ";
p=p->next;
}
cout<<endl;
}
void main()
{
LinkList first=NULL;
InsertList(first, 10);
InsertList(first, 20);
InsertList(first, 26);
InsertList(first, 45);
InsertList(first, 33);
InsertList(first, -78);
InsertList(first, 14);
InsertList(first, -71);
PrintList(first);
// reverse1(first);
reverse2(first);
PrintList(first);
}