-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-Nodes-from-Linked-list.java
More file actions
43 lines (37 loc) · 1.03 KB
/
Remove-Nodes-from-Linked-list.java
File metadata and controls
43 lines (37 loc) · 1.03 KB
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
41
42
43
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNodes(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode next = null;
while(cur != null){
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
// Result head
ListNode resHead = new ListNode(prev.val);
int MAX = resHead.val; // last value include must, becz its right == null
cur = prev.next;
while(cur != null){
ListNode node = new ListNode(cur.val);
if(cur.val >= MAX){
node.next = resHead;
resHead = node;
MAX = node.val;
}
cur = cur.next;
}
return resHead;
}
}