Leetcode:partition List Problem Solving report

Source: Internet
Author: User

Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to X.

You should preserve the original relative order of the nodes in each of the.

For example,
Given 1->4->3->2->5->2 and x = 3,
Return 1->2->2->4->3->5.

Solution 1:

Note Use Dummynode to record the previous node of the head node of each chain. This allows us to easily retrieve the head node.

1. Go Through the link, find the nodes which is bigger than N, create a new link.

2. After 1 done, just link the other links.

1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9  *     }Ten  * } One  */ A  Public classSolution { -      PublicListNode partition (ListNode head,intx) { -         if(Head = =NULL) { the             return NULL; -         } -          -ListNode dummy =NewListNode (0); +Dummy.next =head; -          +ListNode pre =dummy; AListNode cur =head; at          -         //Record The big list. -ListNode Bigdummy =NewListNode (0); -ListNode Bigtail =Bigdummy; -          -          while(cur! =NULL) { in             if(Cur.val >=x) { -                 //Unlink the cur; toPre.next =Cur.next; +                 -                 //ADD the cur to the tail of the new link. theBigtail.next =cur; *Cur.next =NULL; $                Panax Notoginseng                 //Refresh the Bigtail. -Bigtail =cur; the                 +                 //when you remove an element, the pre does not need to be modified because the cur has moved to the next position.  A}Else { thePre =Pre.next; +             } -              $Cur =Pre.next; $         } -          -         //Link the Big linklist to the smaller one. thePre.next =Bigdummy.next; -         Wuyi         returnDummy.next; the     } -}
View Code

CODE:

Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/Partition.java

Leetcode:partition List Problem Solving report

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.