206. Reverse Linked List
Reverse a singly linked list.
时间复杂度O(n),空间复杂度O(1)
/**
* 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* tail = NULL;
ListNode* ans = NULL;
while (head) {
tail = head->next;
head->next = ans;
ans = head;
head = tail;
}
return ans;
}
};
92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.
反转部分链表,精髓还是反转链表。反转链表需要定义三个结点【敲黑板】,一个是答案,一个是当前结点,一个是前一个结点。时间复杂度O(n),空间复杂度O(n)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (!head) return head;
ListNode node(0);
ListNode* ans = &node;
ans->next = head;
for (int i = 0; i < m - 1; ++i) {
ans = ans->next;
}
ListNode* pre = ans->next;
for (int i = 0; i < n - m; ++i) {
ListNode* cur = pre->next;
pre->next = cur->next;
cur->next = ans->next;
ans->next = cur;
}
return node.next;
}
};