Solution 1
0092. Reverse Linked List II 的简化版,默认边界为头和尾,从头到尾进行逆转。
因此可以在此题实现的基础上进行改动,简化判定和后处理(从边界重新连接)的逻辑。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的节点个数,完成一次线性遍历
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个线性变量(若干指针)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
auto tail = head;
if (head != nullptr) {
auto afterTail = head->next;
while (afterTail != nullptr) {
auto afterAfterTail = afterTail->next;
afterTail->next = tail;
tail = afterTail;
afterTail = afterAfterTail;
}
head->next = nullptr;
}
return tail;
}
};
Solution 2
Solution 1的Python实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
tail = head
if head is not None:
afterTail = head.next
while afterTail is not None:
afterAfterTail = afterTail.next
afterTail.next = tail
tail = afterTail
afterTail = afterAfterTail
head.next = None
return tail