LeetCode143—Reorder List

我不是女神ヾ 2022-07-16 02:21 235阅读 0赞

原题

原题链接

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}.


分析

比较简单的思路就是,按照原链表反着重新创建一个链表,然后69式,删去新链表里面多于的部分。
不过题目又说不让用多于的空间,只能“in place”,原地进行调整。

那就把链表拆开,分为两个链表,前半部分和后半部分。
1.前半部分不用修改。
2.后半部分做逆置操作。
3.69式插入

代码

  1. class Solution
  2. {
  3. private:
  4. void reverse(ListNode * &post)//逆置链表
  5. {
  6. if(post&&post->next)
  7. {
  8. ListNode *p1 = post;
  9. ListNode *p2 = post->next;
  10. ListNode *p3 = NULL;
  11. while(p2!=NULL)
  12. {
  13. p3=p2->next;
  14. p2->next=p1;
  15. p1=p2;
  16. p2=p3;
  17. }
  18. post->next=NULL;
  19. post=p1;
  20. }
  21. else
  22. {
  23. return ;
  24. }
  25. }
  26. public:
  27. void reorderList(ListNode * head)
  28. {
  29. if(!head)
  30. return ;
  31. int count=0;
  32. ListNode *p=head;
  33. while(p!=NULL)
  34. {
  35. p=p->next;
  36. count++;
  37. }
  38. count = (count+1)/2;//find pre
  39. ListNode *pre=head;
  40. ListNode *post=head;
  41. int t=count;
  42. while(--t)
  43. {
  44. post=post->next;
  45. }
  46. ListNode *r = post;
  47. post=post->next;
  48. r->next=NULL;
  49. //cout << post->val<<endl;
  50. // cout << count << endl;
  51. reverse(post);
  52. ListNode *pPre=pre;
  53. ListNode *pPost=post;
  54. ListNode *pNext=NULL;
  55. while(pPost)
  56. {
  57. pNext=pPost->next;
  58. pPost->next=pPre->next;
  59. pPre->next=pPost;
  60. pPre=pPost->next;
  61. pPost=pNext;
  62. }
  63. head=pre;
  64. }
  65. };

发表评论

表情:
评论列表 (有 0 条评论,235人围观)

还没有评论,来说两句吧...

相关阅读