力扣86. 分隔链表

1.需要新建两个链表,一个存取比x小的,另一个存取大于等于x的
2.将1中的两个链表合并

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* partition(ListNode* head, int x) {
14         ListNode *vhead_less = new ListNode(-1);
15         ListNode *vhead_greater = new ListNode(-1);
16         ListNode *pre, *cur, *next; //维护前、当前、下一个节点
17         ListNode *lhead = vhead_less, *ghead = vhead_greater;
18         pre = nullptr;
19         cur = head;
20         while(cur) {
21             next = cur -> next;
22             if (x > cur -> val) {
23                 vhead_less -> next = cur; //尾插法创建链表
24                 vhead_less = cur; //更新尾节点
25             } else{
26                 vhead_greater -> next = cur;
27                 vhead_greater = cur;
28             }
29             pre = cur;
30             cur = next;
31         }
32         vhead_greater -> next = nullptr; //将最后一个元素的next置空
33         vhead_less -> next = ghead -> next; //合并链表
34         return lhead -> next;
35     }
36 };

 

posted on 2025-03-03 15:06  Coder何  阅读(14)  评论(0)    收藏  举报