【15】反转链表
- 时间限制:1秒
- 空间限制:32768K
- 本题知识点: 链表
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
牛客网题目链接:点击这里
vs2010代码
#include<iostream>
#include<vector>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
vector<int> temp;
ListNode* P=pHead;
while(P!=NULL)
{
temp.push_back(P->val); //将值顺序存入数组
P=P->next;
}
P=pHead;
int i=temp.size()-1;
while(P!=NULL)
{
P->val=temp[i];
i--; P=P->next;
}
return pHead;
}
};
int main()
{
Solution S1;
ListNode* H=NULL;
ListNode* Cur=NULL;
ListNode* s=NULL;
//建立头结点
int t;
cout<<"输入5个结点"<<endl;
cout<<"输入第1个结点:";
cin>>t;
s=new ListNode(t);
H=s; Cur=s;
for(int i=1; i<5; i++)
{
cout<<"输入第"<<i+1<<"个结点:";
cin>>t;
s=new ListNode(t);
Cur->next=s;
Cur=Cur->next;
}
//cout<<endl;
//S1.ReverseList(H);
//输出结点
cout<<endl;
//Cur=H;
Cur=S1.ReverseList(H);
while(Cur)
{
cout<<Cur->val<<"->";
Cur=Cur->next;
}
}
方法二:
三指针反转链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return NULL;
ListNode* Head=pHead;
ListNode* p1=pHead;
ListNode* p2=NULL;
while(p1->next!=NULL){
p1=p1->next;
Head->next=p2;
p2=Head;
Head=p1;
}
Head->next=p2;
return Head;
}
};
代码优化:
ListNode* ReverseList(ListNode* pHead)
{
ListNode* pReverseHead=NULL;
ListNode* pNode=pHead;
ListNode* pPrev=NULL;
while(pNode)
{
ListNode* pNext=pNode->next;
if(pNext==NULL)
pReverseHead=pNode;
pNode->next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return pReverseHead;
}