-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion2487.java
More file actions
62 lines (56 loc) · 1.11 KB
/
Copy pathQuestion2487.java
File metadata and controls
62 lines (56 loc) · 1.11 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Author: Ananthanarayanan R
Section: Algorithms
Question: 2487
*/
public class Question2487
{
public static ListNode reverse(ListNode head)
{
if(head==null || head.next==null)
return head;
ListNode p1 = null;
ListNode p2 = head.next;
while(head!=null && p2!=null)
{
head.next = p1;
p1 = head;
head = p2;
p2 = head.next;
}
head.next = p1;
p1 = head;
return p1;
}
public static ListNode removeNodes(ListNode head)
{
if(head==null || head.next == null)
return head;
ListNode rev = reverse(head);
ListNode temp = rev;
int max = temp.val;
ListNode previous = temp;
while(temp!=null)
{
if(temp.val<max)
{
previous.next = temp.next;
}
else
{
max = temp.val;
previous = temp;
}
temp = temp.next;
}
return reverse(rev);
}
public static void main(String[] args)
{
System.out.println("Main Method starts");
ListNode head = LinkedList.create(15,"unsorted");
LinkedList.display(head);
ListNode result = removeNodes(head);
LinkedList.display(result);
}
}