反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
方法一:外部容器
将链表转存至新的容器vector内,再利用vector本身的reverse_iterator进行反向遍历,将内容一一对应存入链表节点内。
/**
* 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 head;
}
vector<int> store;
while (head != NULL)
{
store.push_back(head->val);
head = head->next;
}
ListNode* resHead = new ListNode(0);
ListNode* p = resHead;
ListNode* q = nullptr;
p->val = *(store.rbegin());
for (vector<int>::reverse_iterator riter = store.rbegin() + 1; riter != store.rend(); riter++)
{
q = new ListNode(0);
q->val = *riter;
p->next = q;
p = q;
}
p->next = NULL;
return resHead;
}
};
复杂度分析
- 时间复杂度:O(n),其中n为链表长度。
- 空间复杂度:O(n)。
方法二:迭代
在遍历列表时,将当前节点的 next 指针改为指向它的前一个节点。分别需要一个指针用来记录上一个节点(previous),当前节点(current)以及下一个节点(next)。
/**
* 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 head;
}
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != NULL)
{
ListNode* nextTemp = nullptr;
nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
};
复杂度分析
- 时间复杂度:O(n),其中n为链表长度。
- 空间复杂度:O(1)。
方法三:递归
递归方法比较难理解,假设我们传入的链表为1->2->3->4->5->NULL
,那么传入的head
即节点1
,递归令节点curr
等于reverseList(head->next)
,终止条件为head或head->next为空
,并返回head
。
在这个例子中,最后一层返回的即节点5
,此时head
指向节点4
,我们令head->next->next = head
,即1->2->3->4->5->4
:
01
接着,令head->next = null
,即1->2->3->4->null
且5->4
:
02
/**
* 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 || head->next == NULL)
{
return head;
}
ListNode* curr = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return curr;
}
};
复杂度分析
- 时间复杂度:O(n),其中n为链表长度。
- 空间复杂度:O(n),递归至n层。