[Leetcode]86. Partition List@java Problem Solving report __java

Source: Internet
Author: User

https://leetcode.com/problems/partition-list/description/


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

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

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




Given a single linked list and an X, put less than X in the list to the front, greater than or equal to X to the back, the original relative position of each element is unchanged.

Train of thought: new two nodes preHead1 and preHead2, respectively, point to two linked list of the head node.

A node with a node value of less than X is linked to the list 1, and nodes with a node value equal to X are linked to the list 2.

Finally, two linked lists can be connected

Package go.jacob.day817;

/**
 * 86. Partition List
 * 
 * @author Jacob
 *
/public class Demo3 {public
	listnode Partition (listnode Head, int x) {
		//prehead1 and preHead2 are the forward nodes of two linked header nodes (one linked list has a node value less than x, another greater than equal x)
		ListNode preHead1 = new ListNode (0), PreHead2 = new ListNode (0);
		ListNode cur1 = preHead1, cur2 = preHead2;
		While [head!= null] {
			if (Head.val < x) {
				cur1.next = head;
				Cur1 = Cur1.next;
			} else {
				cur2.next = head;
				CUR2 = Cur2.next;
			}
			head = Head.next;
		}
		Cur1.next = Prehead2.next;
		Cur2.next = null;
		Return Prehead1.next

	}
}





Related Article

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.