20170814_逆置单链表(2种方法)
/*输入一个单链表的头指针head,输出该单链表的逆置单链表。
*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;
//单链表节点
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr) {}
};
//尾插法建立一个单链表
ListNode *CreatList(const vector<int> &a)
{
int ListSize=a.size();
if(ListSize<1)
return nullptr;
else
{
ListNode *root=new ListNode(a[0]);
ListNode *r=root;
for(int i=1; i<ListSize; ++i)
{
ListNode *s=new ListNode(a[i]);
r->next=s;
r=s;
}
return root;
}
}
//顺序输出一个单链表
void OutList(ListNode *root)
{
ListNode *p=root;
while(p!=NULL)
{
if(p->next!=NULL)
cout<<p->val<<", ";
else
cout<<p->val;
p=p->next;
}
cout<<endl;
}
//逆置单链表1:使用头插法逆置
ListNode *ReverseList(ListNode *head)
{
if(head==nullptr || head->next==nullptr)
return head;
ListNode *temp=new ListNode(0);
temp->next=head;
head=head->next;
temp->next->next=nullptr;
ListNode *pNext=nullptr;
while(head)
{
pNext=head->next;
head->next=temp->next;
temp->next=head;
head=pNext;
}
head=temp->next;
delete temp;
temp=nullptr;
return head;
}
//逆置单链表2:原地逆转法(面试时候倾向于这个简单明了的方法!)
ListNode *ReverseList2(ListNode *head)
{
if(head==nullptr || head->next==nullptr)
return head;
ListNode *pPre=nullptr;
ListNode *pNext=nullptr;
while(head)
{
pNext=head->next;
head->next=pPre;
pPre=head;
head=pNext;
}
head=pPre;
return head;
}
int main(void)
{
int num[]={1,2,3,4,5,6,7,8,9,10,100,200,300,400};
vector<int> a(begin(num),end(num));
ListNode *root=CreatList(a);
cout<<"单链表建立完成."<<endl;
cout<<"顺序输出单链表:";
OutList(root);
cout<<endl;
cout<<"方法1:逆置单链表:";
ListNode *head=ReverseList(root);
OutList(head);
cout<<endl;
cout<<"方法2:逆置单链表:";
ListNode *head2=ReverseList(head);
OutList(head2);
cout<<endl;
system("pause");
return 0;
}