当前位置: 首页 > 文档资料 > LeetCode 题解 >

Linked List - Reverse Linked List

优质
小牛编辑
135浏览
2023-12-01

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.

这题要求我们翻转[m, n]区间之间的链表。对于链表翻转来说,几乎都是通用的做法,譬如p1 -> p2 -> p3 -> p4,如果我们要翻转p2和p3,其实就是将p3挂载到p1的后面,所以我们需要知道p2的前驱节点p1。伪代码如下:

  1. //保存p3
  2. n = p2->next;
  3. //将p3的next挂载到p2后面
  4. p2->next = p3->next;
  5. //将p3挂载到p1的后面
  6. p1->next = p3;
  7. //将p2挂载到p3得后面
  8. p3->next = p2;

对于上题,我们首先遍历得到第m - 1个node,也就是pm的前驱节点。然后依次遍历,处理挂载问题就可以了。

代码如下:

  1. class Solution {
  2. public:
  3. ListNode *reverseBetween(ListNode *head, int m, int n) {
  4. if(!head) {
  5. return head;
  6. }
  7. ListNode dummy(0);
  8. dummy.next = head;
  9. ListNode* p = &dummy;
  10. for(int i = 1; i < m; i++) {
  11. p = p->next;
  12. }
  13. //p此时就是pm的前驱节点
  14. ListNode* pm = p->next;
  15. for(int i = m; i < n; i++) {
  16. ListNode* n = pm->next;
  17. pm->next = n->next;
  18. n->next = p->next;
  19. p->next = n;
  20. }
  21. return dummy.next;
  22. }
  23. };

Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

这题要求我们按照每k个节点对其进行翻转,理解了链表如何翻转之后很容易处理,唯一需要注意的就是每次k个翻转之后,一定要知道最后一个节点,因为这个节点就是下组的前驱节点了。

  1. ListNode *reverseKGroup(ListNode *head, int k) {
  2. if(k <= 1 || !head) {
  3. return head;
  4. }
  5. ListNode dummy(0);
  6. dummy.next = head;
  7. ListNode* p = &dummy;
  8. ListNode* prev = &dummy;
  9. while(p) {
  10. prev = p;
  11. for(int i = 0; i < k; i++){
  12. p = p->next;
  13. if(!p) {
  14. //到这里已经不够k个没法翻转了
  15. return dummy.next;
  16. }
  17. }
  18. p = reverse(prev, p->next);
  19. }
  20. return dummy.next;
  21. }
  22. ListNode* reverse(ListNode* prev, ListNode* end) {
  23. ListNode* p = prev->next;
  24. while(p->next != end) {
  25. ListNode* n = p->next;
  26. p->next = n->next;
  27. n->next = prev->next;
  28. prev->next = n;
  29. }
  30. //这里我们会返回最后一个节点,作为下一组的前驱节点
  31. return p;
  32. }