在这种解法中,用到了两个节点来分别记录两个部分的节点的相互关系,很简单明了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode node1(0), node2(0);
ListNode *p1 = &node1, *p2 = &node2;
while (head) {
if (head->val < x)
p1 = p1->next = head;
else
p2 = p2->next = head;
head = head->next;
}
p2->next = NULL;
p1->next = node2.next;
return node1.next;
}
};

但是,在第一次想到得方法是就在这个链表上改动,方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *begin = dummy, *cur = dummy;
while (cur && cur->next) {
if (cur->next->val >= x) cur = cur->next;
else if (begin == cur) {
begin = begin->next;
cur = cur->next;
} else {
ListNode *next = cur->next;
cur->next = next->next;
next->next = begin->next;
begin->next = next;
begin = begin->next;
}
}
return dummy->next;
}
};

在这里,我们有两个指针begincur,这两个指针开始是指向同一个节点dummy的,这就要考虑到拆链表时这两个指针相不相等的问题。

总之,在涉及到两个指针和一个链表时,千万要注意不要同时修改一个节点的信息。