File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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* removeNodes(ListNode* head) {
14
+ if(head->next == nullptr) {
15
+ return head;
16
+ }
17
+ ListNode* prevNode = head;
18
+ ListNode* currentNode = head->next;
19
+
20
+ while(currentNode != nullptr) {
21
+ ListNode* nextNode = currentNode->next;
22
+ currentNode->next = prevNode;
23
+ prevNode = currentNode;
24
+ currentNode = nextNode;
25
+ }
26
+ head->next = nullptr;
27
+ head = prevNode;
28
+
29
+ prevNode = head;
30
+ currentNode = head->next;
31
+ while(currentNode != nullptr) {
32
+ if(currentNode->val < prevNode->val) {
33
+ currentNode = currentNode->next;
34
+ } else {
35
+ ListNode* nextNode = currentNode->next;
36
+ currentNode->next = prevNode;
37
+ prevNode = currentNode;
38
+ currentNode = nextNode;
39
+ }
40
+ }
41
+ head->next = nullptr;
42
+ head = prevNode;
43
+ return head;
44
+ }
45
+ };
You can’t perform that action at this time.
0 commit comments