首页 > 代码库 > (每日算法)LeetCode --- Reverse Linked List II(旋转链表的指定部分)

(每日算法)LeetCode --- Reverse Linked List II(旋转链表的指定部分)

Reverse Linked List II(旋转链表的指定部分)

Leetcode


  1. Reverse a linked list from position m to n. Do it in-place and in one-pass.
  2. For example:
  3. Given 1->2->3->4->5->NULL, m = 2 and n = 4,
  4. return 1->4->3->2->5->NULL.
  5. Note:
  6. Given m, n satisfy the following condition:
  7. 1 m n length of list.

旋转链表的有序部分,思路:

  1. 申请一个辅助链表,将第m到第n个节点依次插入到辅助链表头结点后,完成异地置逆。
  2. 将辅助链表插回到原链表的 m 到 n 之间。
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode *reverseBetween(ListNode *head, int m, int n) {
  12. if(head == nullptr || m >= n)
  13. return head;
  14. ListNode * newHead = new ListNode(0); //原链表前增加头结点
  15. newHead->next = head;
  16. ListNode * tempHead = new ListNode(0); //辅助链表的头结点
  17. ListNode * pre = newHead; //需要置逆的前一个节点
  18. int i = 1; //第i个节点,永远指向需要被删除的那么节点
  19. while(pre->next != nullptr && i < m) //将i指向第m个节点,pre指向第m-1个节点
  20. {
  21. pre = pre->next;
  22. i++;
  23. }
  24. //这里是否需要判断没有到第m个节点?
  25. if(i < m) return head;
  26. ListNode * p = nullptr;
  27. while(i <= n && pre->next != nullptr)
  28. {
  29. p = pre->next;
  30. pre->next = p->next; //在原链表上去掉第i个节点
  31. p->next = tempHead->next;
  32. tempHead->next = p; //将第i个节点添加到辅助链表上
  33. i++;
  34. }
  35. p = tempHead;
  36. while(p->next != nullptr) //p指向辅助链表的最后一个节点
  37. p = p->next;
  38. p->next = pre->next;
  39. pre->next = tempHead->next; //将辅助链表除头结点以外部分插入到原链表pre后面
  40. return newHead->next;
  41. }
  42. };

(每日算法)LeetCode --- Reverse Linked List II(旋转链表的指定部分)