Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to build a LinkedList

LinkedList

How to build a LinkedList

by  FredrikN  Posted    (Edited  )
This is an example how you can use a LinkedList to add cars
and then write out the data .

Any questions can be send to fredrick.n@thegate.nu

-----------------------------------------------------------

public class Driver
{

public static void main(String[] arg)
{

LinkedList list = new LinkedList();

list.addCar("Porsche 911",312,1994);
list.addCar("Porsche 911",284,1992);
list.addCar("BMW M3 ",286,1993);
list.addCar("Volvo 850",170,1992);
list.addCar("VW VR6",170,1997);

//Method to print all objects in List

System.out.println(list.viewAll());

}
}

-----------------------------------------------------------
import java.util.*;
public class LinkedList
{

private CarNode head = null;

public void addCar(String name , int hk , int year)
{
//If head = null then create the first node
if(head == null)
{
head = new CarNode(name,hk,year,null);
}
else
{
//If there are more than 1 node
head = new CarNode(name,hk,year,head);
}

}



public String viewAll()
{

StringBuffer str = new StringBuffer();

for(CarNode cursor = head ; cursor != null ; cursor = cursor.getNext())
{
//Appending car by car until there are no more cars
str.append(cursor+"\n");
}
return new String(str);

}


}
-----------------------------------------------------------
public class CarNode
{
private String namn;
private int hk;
private int year;
private CarNode next;

public CarNode(String namn,int hk,int year,CarNode next)
{
this.namn = namn;
this.hk = hk;
this.year = year;
this.next = next;

}



public CarNode getNext()
{
return next;
}


public String toString()
{
return namn + " " + hk + " " + year;
}
}
-----------------------------------------------------------
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top