题目链接: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的节点放到右侧,要保持原有的相对顺序。
思路比较简单,用l标识左侧小于x的节点的最后位置,则每次右移r,当r指向的节点小于x时,把其放到l后面即可。
时间复杂度:O(n)
空间复杂度:O(1)
1 class Solution
2 {
3 public:
4 ListNode *partition(ListNode *head, int x)
5 {
6 ListNode *h = new ListNode(0);
7 h -> next = head;
8
9 ListNode *l = h, *r = h;
10 while(r -> next != NULL)
11 {
12 if(r -> next -> val < x)
13 {
14 if(l != r)
15 {
16 ListNode *tempr = r -> next -> next;
17 r -> next -> next = l -> next;
18 l -> next = r -> next;
19 l = r -> next;
20 r -> next = tempr;
21 }
22 else
23 {
24 l = l -> next;
25 r = r -> next;
26 }
27 }
28 else
29 r = r -> next;
30 }
31
32 return h -> next;
33 }
34 };