Single Link List Circular in Java

>> 1.28.2008

I am trying to write a program to implement single link list circular in java. Circular mean it has no null value in any next pointer of the node (node.next != null). In a circular linklist, the last node of the link will connects to the first node, so it's like the cycle.

The program still not working well... a little bit confuse in InsertFirst method, it's only working for two node to inputs.. when I try the third.. then the first will not display.. :(

Please somebody help me.....


public class Node {
public int idata;
public double ddata;
public Node next;

/** Creates a new instance of Node */
public Node(int id, double dd) {
idata = id;
ddata = dd;
next = null;
}

public void displayNode(){
System.out.print("{"+idata+","+ddata+"}");
}

}

/** The LinkList Class */

public class SLLC {

private Node head;

/** Creates a new instance of SLLC */
public SLLC() {
head = null;
}

public boolean isEmpty(){
return (head == null);
}

public void insertFirst(int id, double dd){
Node bantu;
Node baru = new Node(id, dd);
baru.next = baru;

if(isEmpty()){
head=baru;
head.next=head;
}
else {
bantu = head;
while(bantu.next != head){
bantu=bantu.next;
}
baru.next = head;
head = baru;
bantu.next = head;
}

}

public void displayList(){
Node current;
current = head;
if(!isEmpty()){
while(current!=head) {
current.displayNode();
current=current.next;
}
}

}

}

1 comments:

Anonymous 29 January 2008 at 15:43  

try this one

public void insertFirst(int id, double dd){
Node bantu;
Node baru = new Node(id, dd);
baru.next = baru;
if(isEmpty()){
head=baru;
head.next=head;
}
else {
if (head.next==head){
baru.next=head;
head.next=baru;
head = baru;
}else {
bantu = head;
while(bantu.next != head){
bantu=bantu.next;
}
baru.next = head;
bantu.next = baru;
head = baru;}
}

}

About This Blog

About This Blog

  © Blogger template Shiny by Ourblogtemplates.com 2008

Back to TOP