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

Linked List - Reorder List

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

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example,

Given {1,2,3,4}, reorder it to {1,4,2,3}.

这题比较简单,其实就是将链表的左右两边合并,只是合并的时候右半部分需要翻转一下。

主要有三步:

  • 快慢指针找到切分链表
  • 翻转右半部分
  • 依次合并

代码如下:

  1. class Solution {
  2. public:
  3. void reorderList(ListNode *head) {
  4. if(head == NULL || head->next == NULL) {
  5. return;
  6. }
  7. ListNode* fast = head;
  8. ListNode* slow = head;
  9. //快慢指针切分链表
  10. while(fast->next != NULL && fast->next->next != NULL){
  11. fast = fast->next->next;
  12. slow = slow->next;
  13. }
  14. fast = slow->next;
  15. slow->next = NULL;
  16. //翻转右半部分
  17. ListNode dummy(0);
  18. while(fast) {
  19. ListNode* n = dummy.next;
  20. dummy.next = fast;
  21. ListNode* nn = fast->next;
  22. fast->next = n;
  23. fast = nn;
  24. }
  25. slow = head;
  26. fast = dummy.next;
  27. //依次合并
  28. while(slow) {
  29. if(fast != NULL) {
  30. ListNode* n = slow->next;
  31. slow->next = fast;
  32. ListNode* nn = fast->next;
  33. fast->next = n;
  34. fast = nn;
  35. slow = n;
  36. } else {
  37. break;
  38. }
  39. }
  40. }
  41. };