//Method sort the list after year the car was made
list.sortList();
//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 void sortList()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(CarNode cursor = head ; cursor.getNext() != null ; cursor = cursor.getNext())
{
if(cursor.getYear() < cursor.getNext().getYear())
{
String n = cursor.getName();
int y = cursor.getYear();
int hk = cursor.getHk();
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 name;
private int hk;
private int year;
private CarNode next;
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.