题目描述(力扣):
思路: 创造两个指针,分别指向大于x的链表和小于x的链表,然后依次遍历初始链表的每个节点进行判断将其添加到对应的新链表中,最后将两个链接进行连接后返回。
代码:
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
31
32
33
34
35
36
37
38
39
40
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x)
{
ListNode *h1 = new ListNode(-1); //指向小于x的节点组成的链表的头节点
ListNode *h2 = new ListNode(-1); //指向大于x的节点组成的链表的头节点
ListNode *t1, *t2; //分别指向各自链表的尾结点
t1 = h1;
t2 = h2;
while(head != nullptr) //遍历每个节点,与x进行比较
{
if(head->val < x)
{
t1->next = head;
t1 = head;
}
else
{
t2->next = head;
t2 = head;
}
head = head->next;
}
t1->next = h2->next; //将两个链表进行连接
t2->next = nullptr;
return h1->next;
}
};
|