LeetCode 86. Partition List
原题链接在这里:https://leetcode.com/problems/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
.
题解:
Two pointers, 若是当前点val比x小,就连在连到left dummy head后面。否则连到right dummy head后面.
Time Complexity: O(n). Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode partition(ListNode head, int x) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode leftDummy = new ListNode(0); //左侧dummy后面链接的点val比x小 16 ListNode rightDummy = new ListNode(0); //右侧dummy后面链接的店val比x大或者相等 17 18 ListNode leftCur = leftDummy; 19 ListNode rightCur = rightDummy; 20 while(head != null){ 21 if(head.val < x){ 22 leftCur.next = head; 23 leftCur = leftCur.next; 24 head = head.next; 25 }else{ 26 rightCur.next = head; 27 rightCur = rightCur.next; 28 head = head.next; 29 } 30 } 31 32 rightCur.next = null; //断开右侧尾节点 33 leftCur.next = rightDummy.next; 34 return leftDummy.next; 35 } 36 }