Leetcode. Reorder List

Source: Internet
Author: User

Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→lnl1→ln-1→l2→l N-2→ ...

You must does this in-place without altering the nodes ' values.

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

1, through the double pointer method to get the midpoint of the list, so that the left and right two linked lists

2. Reverse the right half of the list

3. Merge two linked lists

1 voidReorderlist (ListNode *head)2     {3         if(head = = NULL | | head->next = = NULL | | head->next->next = =NULL)4             return;5         6ListNode *p, *q, *dummy =NewListNode (int_min);7Q =head;8p = q->Next;9          while(P! =NULL)Ten         { OneQ = q->Next; Ap = p->Next; -             if(P! =NULL) -p = p->Next; the         } -          -Dummy->next = q->next;//Right half nodes -Q->next =NULL; +Q = head;//Left half nodes - reverse (dummy); +          A          while(Q! =NULL) at         { -p = dummy->Next; -Dummy->next = p->Next; -P->next = q->Next; -Q->next =p; -Q = q->Next; inQ = q->Next; -             if(Dummy->next = =NULL) to                  Break; +         } -Delete dummy; the     } *      $     voidReverse (ListNode *dummy)Panax Notoginseng     { -ListNode *p = Dummy, *q, *R; the          +Q = p->Next; A         if(q = =NULL) the             return; +r = q->Next; -          while(r! =NULL) $         { $Q->next =p; -p =Q; -Q =R; ther = r->Next; -         }WuyiQ->next =p; theDummy->next->next =NULL; -Dummy->next =Q; Wu}

Leetcode. Reorder List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.