題目描述
給定鏈表和整型值x,將小於x的結點放到鏈表左邊,大於x的結點放到鏈表右邊。
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的結點插入到右鏈表的尾部,然後將左鏈表的尾結點指向右鏈表的頭結點,然後返回左鏈表的頭結點。
代碼實現
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return head;
}
ListNode leftHead = new ListNode(0);//左鏈表的頭結點
ListNode leftTail = leftHead;//左鏈表的尾結點
ListNode rightHead = new ListNode(0);//右鏈表的頭結點
ListNode rightTail = rightHead;//右鏈表的尾結點
ListNode p = head;
while (p != null) {
if (p.val < x) {
leftTail.next = p;
leftTail = leftTail.next;
} else {
rightTail.next = p;
rightTail = rightTail.next;
}
p = p.next;
}
//將左鏈表的尾結點指向右鏈表的頭結點
leftTail.next = rightHead.next;
//將右鏈表的尾結點的下一個結點置爲空
rightTail.next = null;
//返回新的頭結點
return leftHead.next;
}
}