-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveNodesFromLinkedList2487.java
59 lines (51 loc) · 1.48 KB
/
RemoveNodesFromLinkedList2487.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class RemoveNodesFromLinkedList2487 {
/*
* You are given the head of a linked list.
*
* Remove every node which has a node with a greater value anywhere to the right side of it.
*
* Return the head of the modified linked list.
*/
//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) {
head = revList(head);
int max = 0 ;
ListNode prev = null ;
ListNode curr = head ;
while (curr != null) {
max = Math.max(max , curr.val);
if (curr.val < max){
prev.next = curr.next ;
ListNode del = curr ;
curr = curr.next ;
del.next = null ;
}
else {
prev = curr ;
curr = curr.next;
}
}
return revList(head);
}
private ListNode revList (ListNode head){
ListNode prev = null ;
ListNode curr = head ;
ListNode nxt = null ;
while (curr != null) {
nxt = curr.next ;
curr.next = prev ;
prev = curr ;
curr = nxt ;
}
return prev ;
}
}
}