題目鏈接:https://leetcode.com/problems/reverse-linked-list/
題目內容:
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
題目分析:
就是經典的反轉鏈表啦~題目的提示還說用迭代和遞歸都實現一遍,我只實現了迭代的寫法,遞歸的網上很多,引用其中一位(作者:雲中孤鶩)。然後第三種寫法是使用棧實現的,雖然消耗多餘的空間,但是遞歸本質上也是一種棧。
遞歸的寫法:
//遞歸方式
ListNode * ReverseList2(ListNode * head)
{
//如果鏈表爲空或者鏈表中只有一個元素
if(head==NULL || head->m_pNext==NULL)
return head;
else
{
ListNode * newhead=ReverseList2(head->m_pNext);//先反轉後面的鏈表
head->m_pNext->m_pNext=head;//再將當前節點設置爲其然來後面節點的後續節點
head->m_pNext=NULL;
return newhead;
}
}
迭代的寫法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
else {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur->next != NULL) {
ListNode* pNext = cur->next;
cur->next = pre;
pre = cur;
cur = pNext;
}
cur->next = pre;
return cur;
}
}
};
使用STL棧實現的寫法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
stack<ListNode*> nodes;
ListNode* lists = head;
while (lists->next != NULL)
{
nodes.push(lists);
lists = lists->next;
}
ListNode* newpHead = lists;
ListNode* newLists = newpHead;
while (!nodes.empty())
{
newLists->next = nodes.top();
newLists = newLists->next;
nodes.pop();
}
newLists->next = NULL;
return newpHead;
}
};