-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReOrderLL.java
More file actions
98 lines (88 loc) · 2.16 KB
/
ReOrderLL.java
File metadata and controls
98 lines (88 loc) · 2.16 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
public class ReOrderLL {
static ListNode head =null;
static ListNode ans =null;
private static class ListNode{
private int val;
private ListNode next;
public ListNode(int v, ListNode next){
this.val=v;
this.next=next;
}
}
static int length(ListNode temp){
int l=0;
while(temp!=null){
temp = temp.next;
l++;
}
return l;
}
static void add(int pos, int val){
ListNode node = new ListNode(val,null);
ListNode temp = head;
int t=0;
if(temp == null || pos ==0){
node.next =head;
head = node;
}
else{
while(t<pos-1 && temp!=null){
temp = temp.next;
t++;
}
node.next = temp.next;
temp.next=node;
}
}
static void addAns(int pos, int val){
ListNode node = new ListNode(val,null);
ListNode temp = ans;
int t=0;
if(temp == null || pos ==0){
node.next =ans;
ans = node;
}
else{
while(t<pos-1 && temp!=null){
temp = temp.next;
t++;
}
node.next = temp.next;
temp.next=node;
}
}
static ListNode reOrder(ListNode l){
int len = length(l);
int t =0, mid = len/2;
while(t<len && l != null){
if(t<=mid){
addAns(length(ans), l.val);
}
else{
addAns(len-t, l.val);
}
l = l.next;
t++;
}
head = ans;
return ans;
}
static void display(){
ListNode temp = head;
while(temp!=null){
System.out.print(temp.val + " ");
temp=temp.next;
}
}
public static void main(String args[]){
add(0, 6);
add(0, 5);
add(0, 4);
add(0, 3);
add(0, 2);
add(0, 1);
reOrder(head);
display();
System.out.println("\n"+length(head));
}
}