如题:
方法一:
直观思维,先可采用vector或者stack将该链表存下来,再新建一个头节点,再从容器中依次取出每个节点构成新链表,最后返回表头即可,注意vector需要反转一下。
采用vector:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return nullptr;
vector<ListNode*> v;
while(pHead)
{
v.push_back(pHead);
pHead = pHead->next;
}
reverse(v.begin(),v.end());
ListNode *New_head = v[0];
ListNode *p = New_head;
for(int i=0;i<v.size();i++)
{
p->next = v[i];
p=p->next;
}
p->next = nullptr;
return New_head;
}
};
采用stack:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return nullptr;
stack<ListNode*> s;
while(pHead)
{
s.push(pHead);
pHead = pHead->next;
}
ListNode *New_head = s.top();
ListNode *p = New_head;
while(!s.empty())
{
p->next = s.top();
s.pop();
p=p->next;
}
p->next = nullptr;
return New_head;
}
};
方法二:
迭代,
具体可参考:Leetcode刷题 206.反转链表 Reverse Linked List
这里核心就在于在反转一个节点时,需要用一个变量来存储当前节点的后驱,不然我们在反转时,把当前节点的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 nullptr;
if(!(pHead->next)) return pHead;
ListNode *pre = NULL;
ListNode *cur = pHead;
ListNode *next = pHead;
while(cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
方法三:
递归;