[InterviewBit] Partition List

Partition List

  • Time :
  • Space :
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::partition(ListNode* A, int B) {
ListNode* less = new ListNode(-1);
ListNode* greater = new ListNode(-1);
ListNode* lrunner = less;
ListNode* grunner = greater;
while(A) {
if(A->val < B) {
lrunner->next = A;
lrunner = lrunner->next;
} else {
grunner->next = A;
grunner = grunner->next;
}
A = A->next;
grunner->next = NULL;
lrunner->next = NULL;
}
lrunner->next = greater->next;
return less->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/15/PS/interviewbit/partition-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.