-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListPracticeFunctions
More file actions
146 lines (135 loc) · 2.86 KB
/
linkedListPracticeFunctions
File metadata and controls
146 lines (135 loc) · 2.86 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
public int listCompare(Node a1, Node a2) {
/*
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
*/
while(a1!=null && a2!=null) {
if((a1.cdata)<(a2.cdata)) {
return -1;
}
else if((a1.cdata)>(a2.cdata)) {
return +1;
}
else if((a1.cdata)==(a2.cdata)) {
a1=a1.next;
a2=a2.next;
}
}
if(a1!=null){
return 1;
}
if(a2!=null){
return -1;
}
return 0;
}
public Node reverseMergeList(Node a1, Node a2){
/*
Input: a: 5->10->15->40
b: 2->3->20
Output: res: 40->20->15->10->5->3->2
*/
Node res = null;
while(a1!=null && a2!=null) {
if(a1.data<=a2.data) {
Node newNode = new Node(a1.data);
if(res==null) {
res = newNode;
}
else {
newNode.next = res;
res = newNode;
}
a1=a1.next;
}
else if(a2.data<a1.data) {
Node newNode = new Node(a2.data);
if(res==null) {
res = newNode;
}
else {
newNode.next = res;
res = newNode;
}
a2=a2.next;
}
}
System.out.println(res.data);
while(a1!=null) {
Node newNode = new Node(a1.data);
if(res==null) {
res = newNode;
}
else {
newNode.next = res;
res = newNode;
}
a1=a1.next;
}
while(a2!=null) {
Node newNode = new Node(a2.data);
if(res==null) {
res = newNode;
}
else {
newNode.next = res;
res = newNode;
}
a2=a2.next;
}
return res;
}
public Node reverseList(Node x){
Node curr=x;
Node prev=null;
Node next=null;
while(curr!=null) {
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
public Node rearrangeList(Node x) {
/*
Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 5 -> 2 -> 4 -> 3
*/
Node slow = x;
Node fast = x.next;
while(fast!=null && fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
Node revFirst = reverseList(slow.next);
slow.next = null; //needs to cout off the fwd and bckwd lists
Node first = x;
Node second = revFirst;
Node res = null;
printList(first);
printList(second);
while(first!=null || second!=null) {
if(first!=null) {
if(res==null)
res= first;
else {
res.next=first;
res = res.next;
}
first= first.next;
}
if(second!=null) {
res.next = second;
res = res.next;
second=second.next;
}
}
return x;
}