-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListNode.java
60 lines (53 loc) · 1.43 KB
/
ListNode.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
60
public class ListNode {
int value;
ListNode next = null;
public ListNode(int value) {
this.value = value;
}
public ListNode insert (ListNode head, ListNode nodeToInsert) {
nodeToInsert.next = head;
return nodeToInsert;
}
public void printList() {
ListNode itr = this;
while (itr != null) {
System.out.print(itr.value + " ");
itr = itr.next;
}
}
public String toString() {
StringBuilder b = new StringBuilder();
b.append(this.value);
return b.toString();
}
public ListNode oddEvenSort() {
ListNode current = this;
ListNode odd = this.next;
ListNode firstOdd = odd;
ListNode even = odd.next;
ListNode firstEven = current;
odd.next = current;
current.next = even;
current = even;
while (current.next != null) {
odd.next = current.next;
odd = odd.next;
even = odd.next;
odd.next = firstEven;
current.next = even;
current = even;
}
return firstOdd;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head = head.insert(head, new ListNode(2));
head = head.insert(head, new ListNode(3));
head = head.insert(head, new ListNode(4));
head = head.insert(head, new ListNode(5));
head.printList();
System.out.println("\n");
head = head.oddEvenSort();
head.printList();
}
}