【leetcode每日一题】Reorder List

港控/mmm° 2022-08-04 14:38 255阅读 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}.

解析:先将链表的后半部分反序,得到一个新链表。再把两个链表合并即可。步骤如下:

1)声明两个指针,快指针和慢指针,得到链表中间节点。

2)对链表后半部分进行逆序。

3)合并两个链表。

代码如下:

  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* reverse(ListNode *head)
  12. {
  13. if(head==NULL||head->next==NULL)
  14. return head;
  15. ListNode *p1=head,*p2=head->next,*p3;
  16. while(p2!=NULL)
  17. {
  18. p3=p2->next;
  19. p2->next=p1;
  20. p1=p2;
  21. p2=p3;
  22. }
  23. head->next=NULL;
  24. return p1;
  25. }
  26. ListNode* findMiddle(ListNode *head)
  27. {
  28. if(head==NULL||head->next==NULL)
  29. return head;
  30. ListNode *fast=head,*slow=head,*temp;
  31. while(fast!=NULL&&fast->next!=NULL)
  32. {
  33. fast=fast->next->next;
  34. slow=slow->next;
  35. }
  36. temp=slow->next;
  37. slow->next=NULL;
  38. return temp;
  39. }
  40. void reorderList(ListNode *head) {
  41. if(head==NULL||head->next==NULL)
  42. return;
  43. ListNode *pre=head;
  44. ListNode *tail=findMiddle(head);
  45. ListNode *post=reverse(tail);
  46. ListNode *temp1,*temp2;
  47. while(pre!=NULL&&post!=NULL)
  48. {
  49. temp1=pre->next;
  50. temp2=post->next;
  51. pre->next=post;
  52. post->next=temp1;
  53. pre=temp1;
  54. post=temp2;
  55. }
  56. }
  57. };

发表评论

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

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

相关阅读