原题目
Reverse a singly linked list.
中文大意
实现链表的逆置,通过两种方式(递归和迭代)来实现
题解1:迭代方式
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
//题目的输入中存在空链表,先对这种特殊情况进行处理
if(head==NULL) return NULL;
//找到链表的尾部
ListNode* tail = head;
while(tail->next!=NULL)
tail = tail->next;
//将尾部之前的节点依次插入到尾部后面的位置
ListNode *curr = head;
while(curr!=tail)
{
ListNode *curr_next = curr->next;
ListNode *temp_tail = tail->next;
tail->next = curr;
curr->next = temp_tail;
curr = curr_next;
}
return tail;
}
};
题解1分析
该解法很直观,直接找到链表的尾部,然后从头到尾遍历,依次插入到尾部的后一个节点,注意在插入的时候要先将当前遍历到的节点的next值存起来,然后再将链表接入到尾部节点的后面,然后通过先前存下来的指针遍历下一个节点
题解2:递归方式
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
//当前链表为空或者只有一个节点,无需逆置
if(head==NULL || head->next==NULL)
return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
题解2分析
递归的思路是:将当前节点之后的节点进行逆置,逆置完之后(也就是递归执行完之后)将当前节点插入到逆置后链表的尾部。在插入到尾部有一个技巧,无需用一个循环去找链表的尾部,而是head->next->next
,因为在插入之前,head->next
实际上就是现在的尾部,而head->next->next
也正是尾部的下一个节点
时间、空间复杂度
无论是通过迭代还是递归的方式,都没有额外分配空间,只是对链表的next节点的值进行修改,因此时间复杂度是O(n),空间复杂度是O(1)