題目描述
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
原題鏈接
題目給定的輸入爲一個鏈表的頭節點和一個整型的數字x x x ,以x x x 爲分界符,對原鏈表節點順序重新劃分,小於x x x 的在左側,大於的在右側,但是節點之間的相對位置不變 。
解法1
思路
建立兩個臨時頭節點,一個用作小於x x x 的節點的鏈接,一個用於大於x x x 的鏈接
分別建立兩個工作指針,完成上述節點的鏈接工作,工作指針始終指向當前臨時頭節點所在鏈表的最後一個節點,臨時頭節點的地址保持不變。
遍歷原鏈表,完成上述操作
遍歷完成後,連接上上述部分
代碼
static ListNode partition(ListNode head, int x){
//用於小於x節點的臨時頭節點
ListNode head_less = new ListNode(0);
//工作指針
ListNode ptr_less = head_less;
//用於大於x節點的臨時頭節點
ListNode head_more = new ListNode(0);
ListNode ptr_more = head_more;
while (head!=null){//遍歷原鏈表
if (head.val < x){
//如果小於x,添加到head_less後面
//添加過程由ptr_less來完成
ptr_less.next = head;
ptr_less = head;
}else {
//如果大於x,添加到head_more後面
ptr_more.next = head;
ptr_more = head;
}
head = head.next;//遍歷原鏈表
}
//完成遍歷後,連接兩部分
ptr_more.next = null;
ptr_less.next = head_more.next;
//注意返回新鏈表的第一個節點,而不是臨時頭節點
return head_less.next;
}
細節
注意工作指針的應用,在鏈表的題目裏非常常見
注意完成遍歷後的尾節點的下一個節點應該置空
注意返回的應是新鏈表的第一個節點位置