-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListProblems.java
More file actions
77 lines (70 loc) · 1.62 KB
/
Copy pathLinkedListProblems.java
File metadata and controls
77 lines (70 loc) · 1.62 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
public class LinkedListProblems {
public static void main(String[] args) {
testReverseList();
}
public static ListNode<Integer> generateSequence(int n) {
ListNode<Integer> head = new ListNode<Integer>(1, null);
ListNode<Integer> curr = head;
for(int i = 2; i <= n; i++) {
curr.next = new ListNode<Integer>(i, null);
curr = curr.next;
}
return head;
}
public static ListNode<Integer> reverseList(ListNode<Integer> lst) {
if(lst == null) {
return lst;
}
ListNode<Integer> prev = lst, curr = lst.next, next;
lst.next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public static void testReverseList() {
//System.out.println(reverseList(generateSequence(10)));
System.out.println(reverseListK(generateSequence(8),1));
}
/* Reverse a Linked List in groups of given size */
public static ListNode<Integer> reverseListK(ListNode<Integer> lst, int k) {
if(lst == null) {
return lst;
}
ListNode<Integer> prev = lst, curr = lst.next, next;
ListNode<Integer> head = lst;
lst.next = null;
int counter = 1;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
counter++;
if(counter == k) {
head.next = reverseListK(curr, k);
break;
}
}
return prev;
}
}
class ListNode<T> {
public T data;
public ListNode<T> next;
public ListNode(T data, ListNode<T> next) {
this.data = data;
this.next = next;
}
public String toString() {
String str = this.data+"";
if(this.next != null) {
str += ",";
str += this.next.toString();
}
return str;
}
}