Raitei
2009-08-30 15:17:30 UTC
package linkedlist;
public class LinkedList {
private class node{
int data;
node next;
}
private node first;//pointer to the first node in the list
public LinkedList(){ //create an empty linked list
first = null;
}
public boolean empty(){ // return true if the list is empty, otherwise return false
if(first == null){
return true;
}else
return false;
}
public void InsertinFront(int x){//insert a value x in front of the list
node newptr = first;
newptr = new node();
newptr.data = x;
newptr.next = first;
first = newptr;
}
public void InsertAtEnd (int x) {
node last = first;
while(last != null) {
last = last.next;
}
node newptr = new node();
newptr = last.next;
newptr.next = null;
newptr.data = x;
}
public void Delete(int x){//if value x is in the list, remove x
node dptr = first;
node preptr = first;
while(dptr.data != x){
dptr = dptr.next;
}
preptr.next = dptr.next;
}
public void Display(){// Display the data values in the linked list
node p = first;
while(p != null){
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
public int count(){//Count and return the number of values in the linked list
int count = 0;
node p = first;
while(p != null){
count++;
p = p.next;
}
return count;
}
public static void main(String[] arg){
LinkedList X = new LinkedList();
for(int a = 1; a < 10; a++){
if((a % 2) == 0)
X.InsertAtEnd(a);
}
X.Display();
X.InsertinFront(0);
System.out.println("list after inserting 0:");
X.Display();
X.Delete (2);
System.out.println ("list after deleting 2:");
X.Display();
X.Delete(6);
System.out.println ("list after deleting 6:");
X.Display();
if(!X.empty())
System.out.println("List is not empty.");
System.out.println("Number of values:"+ X.count());
}//main
}//class