Question
输入一个链表,反转链表后,输出新链表的表头。
关键词:链表 反转
Solution
遍历反转
时间复杂度:O(N)
空间复杂度:O(1)
- Python
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead:
return pHead
else:
head = pHead
tail = head.next
head.next = None
while tail:
tail.next, tail, head = head, tail.next, tail
return head
- C++
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (!pHead || !pHead->next)
return pHead;
ListNode* head = pHead;
ListNode* tail = pHead->next;
head->next = NULL;
while(tail){
ListNode* temp1 = tail->next;
tail->next = head;
ListNode* temp2 = tail;
tail = temp1;
head = temp2;
}
return head;
}
};
递归
时间复杂度:O(N)
空间复杂度:O(…)
- Python
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
## 终止条件
if not pHead or not pHead.next:
return pHead
## 递归
re_head = self.ReverseList(pHead.next)
pHead.next.next = pHead
pHead.next = None
## 每轮返回值为已反转的链表表头,即永远是原链表的表尾
return re_head
- C++
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
// 终止条件
if (!pHead || !pHead->next)
return pHead;
// 递归
ListNode* re_head = ReverseList(pHead->next);
// 每轮递归的额外操作
pHead->next->next = pHead;
pHead->next = NULL;
return re_head;
}
};