【Leetcode】【Medium】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
.
解题思路:
1、先条件:输入链表不为空;
2、表头可能改变,因此需要新建一个结点指向表头,或使用二维指针;
3、不变参数:
curNode永远指向待操作结点的前驱(方便删减)
small_end永远指向已经分割的所有小结点中,最后一个结点
big_begin永远指向已经分割的所有大结点中,第一个结点
small_end->next = big_begin;
4、curNode->next为NULL时,循环结束。当发现小结点时,插入small_end和big_begin中间;
代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* partition(ListNode* head, int x) { 12 if (head == NULL) 13 return head; 14 ListNode* prehead = new ListNode(0); 15 prehead->next = head; 16 ListNode* curNode = prehead; 17 ListNode* small_end = NULL; 18 ListNode* big_begin = NULL; 19 20 while (curNode->next && curNode->next->val < x) 21 curNode = curNode->next; 22 23 small_end = curNode; 24 big_begin = small_end->next; 25 26 while (curNode->next) { 27 if (curNode->next->val < x) { 28 small_end->next = curNode->next; 29 small_end = small_end->next; 30 curNode->next = curNode->next->next; 31 small_end->next = big_begin; 32 } else { 33 curNode = curNode->next; 34 } 35 } 36 37 head = prehead->next; 38 delete prehead; 39 return head; 40 } 41 };