Skip to content

Commit 7e88fd8

Browse files
author
rajat.gupta
committed
added more question
1 parent 7768927 commit 7e88fd8

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

reorder_list.java

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package leetcode;
2+
//https://leetcode.com/problems/reorder-list/
3+
public class reorder_list {
4+
static class ListNode {
5+
int val;
6+
ListNode next;
7+
8+
ListNode() {
9+
}
10+
11+
ListNode(int val) {
12+
this.val = val;
13+
}
14+
15+
ListNode(int val, ListNode next) {
16+
this.val = val;
17+
this.next = next;
18+
}
19+
}
20+
21+
public static void main(String[] args) {
22+
ListNode root = new ListNode(1);
23+
root.next = new ListNode(2);
24+
root.next.next = new ListNode(3);
25+
root.next.next.next = new ListNode(4);
26+
root.next.next.next.next = new ListNode(5);
27+
reorder_list ob1= new reorder_list();
28+
ob1.reorderList(root);
29+
while(root!=null) {
30+
System.out.print(root.val);
31+
root=root.next;
32+
}
33+
}
34+
public void reorderList(ListNode head) {
35+
if(head == null || head.next == null) return ;
36+
ListNode slowPtr = head, fastPtr = head;
37+
ListNode prev = head;
38+
// splitting list
39+
while(fastPtr != null && fastPtr.next != null){
40+
prev = slowPtr;
41+
slowPtr = slowPtr.next;
42+
fastPtr = fastPtr.next.next;
43+
}
44+
prev.next = null;
45+
// reverse
46+
ListNode rev = reverse(slowPtr);
47+
ListNode ptr = head;
48+
// arrange alternatively
49+
while(ptr != null){
50+
ListNode t1 = ptr.next;
51+
ListNode t2 = rev.next;
52+
ptr.next = rev;
53+
if(t1 != null)
54+
rev.next = t1;
55+
ptr = t1;
56+
rev = t2;
57+
}
58+
}
59+
public ListNode reverse(ListNode head){
60+
ListNode p1 = head;
61+
ListNode p2 = head.next;
62+
p1.next = null;
63+
while(p2 != null){
64+
ListNode temp = p2.next;
65+
p2.next = p1;
66+
p1 = p2;
67+
p2 = temp;
68+
}
69+
return p1;
70+
}
71+
72+
}

0 commit comments

Comments
 (0)