LeetCode----- 86.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 two partitions.

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

給定一個鏈表和一個值x,對它進行分區,使得小於x的所有節點都在大於或等於x的節點之前。您應該保留兩個分區中的每一個節點的原始相對順序。

思路:構造兩個新的鏈表less,more,將小於x值的節點依次插入到less鏈表,將大於x值的節點依次到more鏈表。最後more鏈表的最後一個節點指向null,並且將more鏈表插入到less鏈表的後面。

代碼如下:

public class PartitionList {
	public static ListNode partition(ListNode head, int x) {
		if(head == null || head.next == null ) {
			return head;
		}
		ListNode less = new ListNode(0);
		ListNode more = new ListNode(0);
		ListNode node = head,pre = less,front = more;
		while(node != null) {
			if(node.val < x) {
				pre.next= node;
				pre = pre.next;
			}else {
				front.next = node;
				front = front.next;
			}
			node = node.next;
		}
		front.next = null;
		pre.next = more.next;
		return less.next;
	}

	public static void main(String[] args) {
		ListNode l10 = new ListNode(1);
		ListNode l11 = new ListNode(2);
		ListNode l12 = new ListNode(3);		
		ListNode l13 = new ListNode(2);
		ListNode l14 = new ListNode(5);
		ListNode l15 = new ListNode(2);
		l10.next = l11;
		l11.next = l12;
		l12.next = l13;
		l13.next = l14;
		l14.next = l15;
		l15.next = null;
		
		ListNode node = partition(l10,3);
		while(node != null) {
			if(node.next == null) {
				System.out.println(node.val);
			}else{
				System.out.print(node.val +"->");
			}
			node = node.next;
		}
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章