1 Implement the portions of Node and List that we have cover
Solution
Note : I have modified the method valueAt() of linklist class. The method which appeared in the question was not correct. And i have also included check for wrong input.
import java.util.NoSuchElementException;
class Node {
private int value;
private Node next;
//Constructors
public Node() {
value = 0;
next = null;
}
public Node(int v) {
value = v;
next = null;
}
public Node(int v, Node n) {
value = v;
next = n;
}
// Accessors
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
// mutators
public void setValue(int value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
// Additional
@Override
public String toString() {
return \"Node: \" + value;
}
}
class LinkList {
private Node start, end;
private int size;
//Constructors
public LinkList() {
start = null;
end = null;
size = 0;
}
//Mutators
public void append(int x) {
if (size == 0) {
start = new Node(x);
end = start;
} else {
Node temp = new Node(x);
end.setNext(temp);
end = temp;
}
size++;
}
public int valueAt(int i) {
if(i<0 || i>=size){
throw new NoSuchElementException();
}else if (i == 0) {
return start.getValue();
} else if (i == size - 1) {
return end.getValue();
} else {
int currentIndex = size;
Node temp = start;
while (i < currentIndex) {
currentIndex--;
temp = temp.getNext();
}
return temp.getValue();
}
}
}
public class Test {
public static void main(String[] args) {
Node node1 = new Node();
System.out.println(node1);
Node node2 = new Node(10);
System.out.println(node2);
Node node3 = new Node(20, node2);
System.out.println(node3);
LinkList linklist=new LinkList();
linklist.append(20);
linklist.append(40);
linklist.append(60);
linklist.append(80);
System.out.println(\"value at 2nd position : \"+linklist.valueAt(2));
}
}
--------------------------------------------------output-----------------------------------------------------------------
Node: 0
Node: 10
Node: 20
value at 2nd position : 60


