Leetcode 86. Partition List

Source: Internet
Author: User

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R 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 .

Test instructions

Given a linked list and a number x, the list partition, less than x is placed in front of greater than or equal to X, and to maintain the relative position of each node within each partition has not changed.

For example, in the original list, 4 in front of 3, 3 in front of 5, after partitioning still maintain this relative position.

Process:

(1) New two linked list, one first, one second,

One is used to record all nodes less than x in the linked list, and one to record all nodes greater than or equal to x in the linked list.

(2) traverse the original linked list.

(3) Finally, the two linked lists are concatenated as the result of the return.

 Public classSolution { PublicListNode partition (ListNode head,intx) {if(Head = =NULL)return NULL; ListNode Firstdummy=NewListNode (0); ListNode Seconddummy=NewListNode (0); ListNode First= Firstdummy, second =Seconddummy;  while(Head! =NULL){            if(Head.val <x) {First.next=Head; First=Head; }Else{Second.next=Head; Second=Head; } head=Head.next; } First.next=Seconddummy.next; Second.next=NULL; returnFirstdummy.next; }}

Leetcode 86. Partition 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.