In: Computer Science
JAVA
/**
* dataAtPosition returns the int data at the described position.
* if the position is an invalid position it throws an Exception.
*
* Examples:
* pos : 0 and LinkedList : 2 --> 3 --> null ==> return 2
* pos : 1 and LinkedList : 1 --> -3 --> null ==> return -3
* pos : 2 and LinkedList : -2 --> 3 --> -2 --> null ==> return -2
*/
Code I have is:
public int dataAtPosition(int pos) {
return 0;
}
package snippet;
public class LinkedList<T> {
private Node<T> head;
private Node<T> tail;
//function to add data
public void add(T element){
Node<T> nd = new Node<T>();//create new node
nd.setValue(element);//set value to node
//if list is empty,create head node
if(head == null){
head = nd;
tail = nd;
} else {
tail.setNext(nd);//insert node to end
tail = nd;
}
System.out.println("Added: "+element);
}
//function to display linked list
public void Display(){
Node<T> tmp = head;//start from head
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue());//print node data
tmp = tmp.getNext();//go to next node
}
}
public int dataAtPosition(int pos) {
Node<T> tmp = head;
while(true)
{
if(tmp == null)//break if list is empty
{
break;
}
if(pos==0)
break;
tmp = tmp.getNext();//go to next node
pos--;
}
return (int) tmp.getValue();
}
public boolean contains(int elem) {
Node<T> tmp = head;
while(true)
{
if(tmp == null)//break if list is empty
{
break;
}
int data=(int) tmp.getValue();//get value of node
if(data==elem)//compare value of current node with elem
return true;
else
tmp = tmp.getNext();//go to next node
}
return false;//if nothing matches return false
}
public static void main(String a[]){
LinkedList<Integer> ll = new
LinkedList<Integer>();
ll.add(2);
ll.add(3);
System.out.println("Linked List is ");
ll.Display();
System.out.println("Data st position 0
"+ll.dataAtPosition(0));
}
}
class Node<T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNext() {
return nextRef;
}
public void setNext(Node<T> ref) {
this.nextRef = ref;
}
@Override
public int compareTo(T arg) {
if(arg == this.value){
return 0;
} else {
return 1;
}
}
}
================================
Output:
Added: 2
Added: 3
Linked List is
2
3
Data st position 0 2