86. 分隔链表
给你一个链表的头节点 head
和一个特定值 x
,请你对链表进行分隔,使得所有 小于 x
的节点都出现在 大于或等于 x
的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2 输出:[1,2]
提示:
- 链表中节点的数目在范围
[0, 200]
内 -100 <= Node.val <= 100
-200 <= x <= 200
题目解析:
分割链表后进行链表拼接
1、新建两个哑结点,分表把小于给定值得节点插入到低端哑结点链表中,不小于给定值得节点放到高端哑结点链表中:
2、拼接两个链表,低链表当前节点的next指向高链表哑结点的next,就把两个链表拼接在一起了:
3、新建一个新的头结点指向低端哑结点的next,释放两个哑结点内存:
4、源码:
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 class ListNode { 7 public: 8 ListNode() : val(0), next(nullptr) {} 9 ListNode(int x) : val(x), next(nullptr) {} 10 ListNode(int x, ListNode *next) : val(x), next(next) {} 11 12 public: 13 int val; 14 ListNode *next; 15 }; 16 17 class Solution { 18 public: 19 ListNode* partition(ListNode *head, int x) { 20 ListNode *lowListDummyHead = new ListNode(0); 21 ListNode *lowListCurrent = lowListDummyHead; 22 ListNode *highListDummyHead = new ListNode(0); 23 ListNode *highListCurrent = highListDummyHead; 24 25 while (head != nullptr) { 26 ListNode *next = head->next; 27 head->next = nullptr; 28 if (head->val < x) { 29 lowListCurrent->next = head; 30 lowListCurrent = lowListCurrent->next; 31 } else { 32 highListCurrent->next = head; 33 highListCurrent = highListCurrent->next; 34 } 35 head = next; 36 } 37 // 拼接两个链表 38 lowListCurrent->next = highListDummyHead->next; 39 ListNode *newHead = lowListDummyHead->next; 40 // 释放两个哑结点内存 41 delete lowListDummyHead; 42 delete highListDummyHead; 43 return newHead; 44 } 45 void insertNodeAtTail(ListNode *&head, int val) { 46 ListNode *newNode = new ListNode(val); 47 ListNode *currentNode = head; 48 if (currentNode == nullptr) { 49 head = newNode; 50 return; 51 } 52 while (currentNode->next != nullptr) { 53 currentNode = currentNode->next; 54 } 55 currentNode->next = newNode; 56 return; 57 } 58 void printfListNode(ListNode *head) { 59 while (head != nullptr) { 60 std::cout << head->val << "->"; 61 head = head->next; 62 } 63 std::cout << "NULL"<< endl; 64 return; 65 } 66 }; 67 68 int main() 69 { 70 Solution *test = new Solution(); 71 vector<int> vec = {1, 4, 3, 2, 5, 2}; 72 ListNode *head = nullptr; 73 for (const auto &v : vec) { 74 test->insertNodeAtTail(head, v); 75 } 76 test->printfListNode(head); // 1->4->3->2->5->2->NULL 77 ListNode *newHead = test->partition(head, 3); 78 test->printfListNode(newHead); // 1->2->2->4->3->5->NULL 79 delete test; 80 system("pause"); 81 return 0; 82 }
5、运行结果: