// Solutions to exercises 3.2, 3.3 and 3.4
class Node {
int val;
Node next;
Node(int x) { val = x; }
public String toString
() { return "Node: " + val
; } }
Node head;
List(Node x
) { head
= x
; }
public void append(Node x) {
if (head==null) {
head = x;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = x;
}
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
s += temp + ", ";
}
return s;
}
// Ex 3.3
public boolean checkCycle() {
Node tortoise = this.head;
Node hare = this.head;
while(true) {
if(hare==null || hare.next==null) {
System.
out.
println("Reached end of list, no cycles"); return false;
}
hare = hare.next.next;
tortoise = tortoise.next;
if(tortoise == hare) {
System.
out.
println("Cycle discovered"); return true;
}
}
}
// Ex 3.4
public Node kthBeforeLast(int k) {
Node temp1 = this.head;
Node temp2 = this.head;
int i = 0;
// Set temp2 to the k+1th element in the list
while(i < k+1) {
if(temp2.next == null) {
return temp1;
}
temp2 = temp2.next;
i++;
}
// Advance both one at the time.
// When temp2 reaches the end, temp1 is at the kth element from end.
while(temp2.next != null) {
temp1 = temp1.next;
temp2 = temp2.next;
}
return temp1;
}
}
class ListEx {
// Ex 3.2
Node a = one.head;
Node b = two.head;
int va, vb;
int remainder = 0;
while (!(a==null && b==null)) {
va = (a==null) ? 0 : a.val; // If one list runs out of numbers,
vb = (b==null) ? 0 : b.val; // use 0 as the value for that position.
int val = va + vb + remainder; // Add remainder from previous round
if(val >= 10) { // Set remainder for this round
remainder = (val - remainder) / 10;
val = val - 10;
} else {
remainder = 0;
}
result.append(new Node(val));
a = (a==null) ? null : a.next;
b = (b==null) ? null : b.next;
}
if (remainder > 0) {
result.append(new Node(remainder));
}
return result;
}
public static void main
(String [] args
) { Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
list.append(two);
list.append(three);
list.append(four);
list.append(five);
//Uncomment for cycle:
//five.next=three;
System.
out.
println(list.
checkCycle());
for (int i=0; i<4; i++) {
System.
out.
print(i
+ "th element before the last: "); System.
out.
println(list.
kthBeforeLast(i
)); }
test571.append(new Node(1));
test571.append(new Node(7));
test571.append(new Node(5));
test634.append(new Node(4));
test634.append(new Node(3));
test634.append(new Node(6));
System.
out.
println("\nAdd lists:"); System.
out.
println(listAdd
(test571, test634
));
test12345.append(new Node(5));
test12345.append(new Node(4));
test12345.append(new Node(3));
test12345.append(new Node(2));
test12345.append(new Node(1));
System.
out.
println("\nAdd lists:"); System.
out.
println(test12345
); System.
out.
println(listAdd
(test12345, test1
)); }
}