Inserting elements into multi-linked list in ascending order - java

I have constructed a multi-linked list made up of Friend objects. The Friend class has name and age field. I am trying to insert the Friend objects in ascending order by comparing the names, but I'm running into issues with the part of my code that handles two matching names.
I'm either getting null pointer exceptions or the printed list is out of order.
Populating the list
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Travis", 19);
l.add("Kyler", 14);
l.add("Abby", 10);
l.add("Bob", 19);
l.add("Travis", 12);
l.add("Zander", 99);
l.printList();
}
LinkedList class:
public class LinkedList {
Friend head;
int listcount;
public LinkedList(){
head = null;
listcount = 0;
}
public void add(String name, int age){
Friend node = new Friend(name,age);
if(head==null){
head = node;
return;
}
if(head.name.compareTo(node.name) > 0){
node.nextName = head;
head = node;
return;
}
Friend current = head;
Friend previous = null;
while(current.name.compareTo(node.name) < 0 && current.nextName != null){
previous = current;
current = current.nextName;
}
if(current.name.compareTo(node.name) == 0 && current.age < node.age){
node.nextName = current.nextName;
current.nextName = node;
}
previous.nextName = node;
node.nextName = current;
}
public void printList(){
Friend temp = head;
while(temp!=null){
temp.print();
temp = temp.nextName;
}
}
}
Friend class:
public class Friend {
String name;
int age;
Friend nextName;
Friend nextAge;
public Friend(String name, int age){
this.name = name;
this.age = age;
nextName = null;
nextAge = null;
}
public void print(){
System.out.println(name+" "+age+". ");
}
}

Please change your add() like this(I mean the last lines of your add() method) ;
if (current.name.compareTo(node.name) == 0 && current.age < node.age) {
node.nextName = current.nextName;
current.nextName = node;
} else if (current.name.compareTo(node.name) < 0 ) {
previous.nextName = current;
current.nextName = node;
} else {
previous.nextName = node;
node.nextName = current;
}
Output
Abby 10.
Bob 19.
Kyler 14.
Travis 12.
Travis 19.
Zander 99.

Related

How to have a String and an int connected in a Single Linked List

I am creating a program that displays the top ten game scores.
The output displays the game score and a name but in my program the names do not match with the score.
It seems that the numbers get sorted correctly - the names do get sorted with the data. The list sorts from highest to lowest. In the output it shows the highest score is:
23 "stan"
when it should show:
23 "tweak"
public class singlyLinked {
class Node {
int data;
String name;
Node next;
public Node(int data, String name) {
this.data = data;
this.name = name;
this.next = null;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
public Node head = null;
public Node tail = null;
int size = 0;
public void addNode(int data, String name) {
Node newNode = new Node(data, name);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void sortList() {
Node current = head;
Node index = null;
int temp;
if (head == null) {
return;
} else {
while (current != null) {
index = current.next;
while (index != null) {
if (current.data < index.data) {
temp = current.data;
current.data = index.data;
index.data = temp;
current.getName();
}
index = index.next;
}
current = current.next;
size++;
}
}
}
public void topTen() {
while (size > 10) {
if (head == null) {
return;
} else {
if (head != tail) {
Node current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
} else {
head = tail = null;
}
}
size--;
}
}
public void getSize() {
System.out.println(size);
}
public void display() {
Node current = head;
if (head == null) {
System.out.println("List is empty");
return;
}
while (current != null) {
System.out.println(current.data + current.name + " ");
current = current.next;
}
}
public static void main(String[] args) {
singlyLinked list = new singlyLinked();
System.out.println("HighScore:" + " Name:");
list.addNode(8, " stan");
list.addNode(7, " kenny");
list.addNode(13, " eric");
list.addNode(12, " wendy");
list.addNode(7, " token");
list.addNode(9, " craig");
list.addNode(1, " clyde");
list.addNode(5, " butters");
list.addNode(20, " randy");
list.addNode(1, " sharon");
list.addNode(22, " timmy");
list.addNode(23, " tweak");
list.sortList(); // sorts
list.topTen();
list.display(); // displays
}
}
Is it required to use your own implementation of LinkedList? If not, you can use something like this:
import java.util.Comparator;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Node> list = new LinkedList<>();
list.add(new Node(8, "stan"));
list.add(new Node(7, "kenny"));
list.add(new Node(13, "eric"));
list.add(new Node(12, "token"));
list.add(new Node(7, "craig"));
list.add(new Node(9, "clyde"));
list.add(new Node(1, "butters"));
list.add(new Node(5, "randy"));
list.add(new Node(20, "sharon"));
list.add(new Node(1, "timmy"));
list.add(new Node(22, "stan"));
list.add(new Node(23, "tweak"));
Collections.sort(list);
for(int i = 0; i < 10; i++){
System.out.println(list.get(i));
}
}
}
class Node implements Comparable<Node>{
String name;
int score;
public Node(int score, String name){
this.score = score;
this.name = name;
}
#Override
public int compareTo(Node another) {
return another.score - this.score;
}
#Override
public String toString() {
return this.name + " : " + this.score;
}
}
So you shouldn't be comparing ints but Nodes.
The standard way of comparing objects in Java is to have them implement Comparable.
class Node implements Comparable<Node> {
// ... your current Node implementation
#Override
public int compareTo(Node that) {
return this.data - that.data;
}
}
Then your sortList should become something like this:
public void sortList() {
Node original = head;
/** Result iteration node. */
Node resultIter = null;
/** The node that is directly before {#code resultIter}. */
Node resultIterPrev = null;
/** A copy of the {#code resultIter} node. */
Node resultIterCopy = null;
/** A temporary node, used for swapping. */
Node temp = null;
if (head == null) {
return;
} else {
// 1. Initialize an empty linked list holding the result.
Node result = null;
// 2.1 Iterate unsorted list
while (original != null) {
// 2.1.1 Scan across the result list to find the location where
// the next element of unsorted list ("original") belongs.
if (result == null) {
result = new Node(original.data, original.name);
} else {
resultIter = result;
boolean added = false;
while (resultIter != null) {
if (original.compareTo(resultIter) > 0) {
resultIterCopy = new Node(resultIter.data, resultIter.name);
temp = resultIter.next;
// Set the value to an existing node so that the pointer
// to "resultIter" remains unchanged
resultIter.data = original.data;
resultIter.name = original.name;
resultIter.next = resultIterCopy;
resultIter.next.next = temp;
added = true;
break;
}
resultIterPrev = resultIter;
resultIter = resultIter.next;
}
// If the next value from the unsorted list belongs at
// the end of the sorted list
if (!added) {
resultIterPrev.next = new Node(original.data, original.name);
}
}
original = original.next;
}
// Swap unsorted list with the sorted one
head = result;
// Find new tail
tail = head;
while (tail.next != null) {
tail = tail.next;
}
}
}
This implementation tries to follow an insertion sort as per described in this answer.
I have extracted size out of your sorting method because it kept increasing every time I invoked sortList. Instead, I've placed it inside addNode:
public void addNode(int data, String name) {
// ... your existing Node adding logic
size++;
}
As you can probably see, creating your own linked list can lead to all sorts of
bugs. Consider using the implementation provided by the Java standard library, as suggested by #LitVitNik.

LinkedList with if statements?

So i got this one task to do, about LinkedList, you can take a look on my Main file, also got to mention that my "//The conditions" part is wrong and I just put something as an idea, but that's actually not really working
import java.util.*;
public class Main {
public static void main(String[] args){
ArrayList nokiaAL = new ArrayList();
LinkedList phoneAL = new LinkedList();
//input
Smartphone a = new Smartphone("Nokia","Nokia 7 Plus",1300,260101);
Smartphone b = new Smartphone("Samsung","Galaxy S8",900,220100);
Smartphone c = new Smartphone("Xiaomi","Mi 10",1500,150031);
Smartphone d = new Smartphone("Nokia","3310",250,101001);
Smartphone e = new Smartphone("Samsung","Galaxy Y",400,774101);
Smartphone f = new Smartphone("Apple","iPhone 7",1100,316300);
phoneAL.insertAtFront(f);
phoneAL.insertAtFront(e);
phoneAL.insertAtFront(d);
phoneAL.insertAtFront(c);
phoneAL.insertAtFront(b);
phoneAL.insertAtFront(a);
//process
Object r = (Object) phoneAL.getFirst();
while (r != null) {
System.out.print(" "+r);
r = (Object) phoneAL.getNext();
}
//The conditions
//If nokia + the price $1200+, it will save all the info about nokia
//If brand samsung + model Galaxy Y, It will count the total of the phone
Object obj;
int countSamsung = 0;
for(int i=0;i<phoneAL.size();i++){
obj = phoneAL.get(i);
Smartphone obj2 = (Smartphone) obj;
if(obj2.getBrand().equalsIgnoreCase("Nokia")){
nokiaAL.add(obj2);
}
if(obj2.getBrand().equalsIgnoreCase("Samsung")){
if(obj2.getModel().equalsIgnoreCase("Galaxy Y")){
countSamsung++;
}
}
}
//output
System.out.println("\n");
System.out.println("Details about Nokia phone more than RM1200:"+nokiaAL.toString());
System.out.println("Quantity of Samsung model Galaxy Y: " + countSamsung);
}
}
I know how to print all the details in the LinkedList, the main point here is, you can't add or change anything of other .java files, you can only edit the Main.java file, is it even possible? here's my Smartphone and LinkedList code.
public class Smartphone {
String brand;//e.g: Nokia, Samsung
String model;//e.g: Lumia, Galaxy Y, Note S
double price;
int warranty;//warranty (in year)
Smartphone() {
}
public Smartphone(String a, String b, double c, int d){
this.brand=a;
this.model=b;
this.price=c;
this.warranty=d;
}
public String getBrand(){
return brand;
}
public String getModel(){
return model;
}
public double getPrice(){
return price;
}
public int getWarranty(){
return warranty;
}
public String toString(){
return "\n\nBrand: "+brand +"\nModel: "+ model +"\nPrice: $"+ price +"\nWarranty: "+ warranty;
}
}
public class LinkedList
{
private Node first;
private Node last;
private Node current;
public LinkedList()
{
first = null;
last = null;
current = null;
}
public boolean isEmpty(){
return (first == null); }
public void insertAtFront(Object insertItem){
Node newNode = new Node(insertItem);
if (isEmpty()){
first = newNode;
last = newNode;
}else{
newNode.next = first;
first = newNode;
}
}
public void insertAtBack(Object insertItem){
Node newNode = new Node(insertItem);
if(isEmpty()){
first = newNode;
last = newNode;
}else{
last.next = newNode;
last = newNode;
}
}
public Object removeFromFront(){
Object removeItem = null;
if(isEmpty()){
return removeItem;
}
removeItem = first.data;
if(first == last){
first = null;
last = null;
}else
first = first.next;
return removeItem;
}
public Object removeFromBack(){
Object removeItem = null;
if(isEmpty())
{
return removeItem;
}
removeItem = last.data;
if (first == last)
{
first = null;
last = null;
}else{
current = first;
while(current.next != last)
current = current.next;
last = current;
last.next = null;
}
return removeItem;
}
public Object getFirst(){
if(isEmpty())
return null;
else
{
current = first;
return current.data;
}
}
public Object getNext(){
if(current == last)
return null;
else
{
current = current.next;
return current.data;
}
}
}
As I said before, I can print all the details of the phones, but how to really use it as conditions, like If-else statement? for example, if(obj.getBrand().equalsIgnoreCase("Nokia")){} , I can achieve this with ArrayList but since this is LinkedList task, So I'm still figuring this out without even know if its possible or not. I hope someone would understand this and able to help. TQ
here's my node code for the LinkedList
public class Node {
Object data;
Node next;
Node(Object obj){
data=obj;
}
}
You should iterate using while and validating if the list has ended.
Diferently from an ArrayList, that you can directly acess the vector positions, in a linked list you should walk from node to node. Also, in your example you only implement a getNext() method and not a get(i).
Example:
Object aux = linkedList.getFirst();
while(aux != null) {
// your business logic here
aux = linkedList.getNext();
}
As you dont make the use of generics in your implementation, to acess your object data, you will need to use cast or make use of generics in your implementation.
Cast way:
while(aux != null) {
phoneObject = (Smartphone) aux;
// your business logic here
if(phoneObject.getBrand().equalsIgnoreCase("Nokia")){
System.out.println("Phone brand == Nokia");
}
aux = linkedList.getNext();
}
In the generic approach, you will also need to change the LinkedList implementation and Node implementation.
LinkedList:
public class LinkedList<T>
{
private Node<T> first;
private Node<T> last;
private Node<T> current;
public T getFirst(){
if(isEmpty())
return null;
else
{
current = first;
return current.data;
}
}
public T getNext(){
if(current == last)
return null;
else
{
current = current.next;
return current.data;
}
}
// add other methods here
}
Node:
public class Node<T> {
T data;
Node<T> next;
// add other methods here
}
Main:
LinkedList<Smartphone> linkedList = new LinkedList<Smartphone>();
// add objects
Smartphone aux = linkedList.getFirst();
while(aux != null) {
// no need to cast, because of generics use
if(aux.getBrand().equalsIgnoreCase("Nokia")){
System.out.println("Phone brand == Nokia");
}
// your business logic here
aux = linkedList.getNext();
}
Your getNext() method, returns null if your list has ended, so our stop criteria is aux == null. Our loop will execute while aux is not null, execute all your business logic (if clauses or what ever validation you want to do) and in the end of the loop, you will set the next object to aux variable.
You should add a generic parameter to your LinkedList.
class LinkedList<T> {
private Node<T> first;
private Node<T> last;
private Node<T> current;
....
}
class Node<T> {
T data;
Node<T> next;
Node(T obj) {
data = obj;
}
}
Then you can only add objects of that type to your list.
LinkedList<Smartphone> phoneList = new LinkedList<>();
But of course, if you can you really should not implement LinkedList by yourself but use the existing one! That's far more easier and safer to use.
List<Smartphone> nokiaList = new ArrayList<>();
List<Smartphone> phoneList = new LinkedList<>();
//input
phoneList.add(new Smartphone("Nokia", "Nokia 7 Plus", 1300, 260101));
phoneList.add(new Smartphone("Samsung", "Galaxy S8", 900, 220100));
phoneList.add(new Smartphone("Xiaomi", "Mi 10", 1500, 150031));
phoneList.add(new Smartphone("Nokia", "3310", 250, 101001));
phoneList.add(new Smartphone("Samsung", "Galaxy Y", 400, 774101));
phoneList.add(new Smartphone("Apple", "iPhone 7", 1100, 316300));
//The conditions
//If nokia + the price $1200+, it will save all the info about nokia
//If brand samsung + model Galaxy Y, It will count the total of the phone
Object obj;
int countSamsung = 0;
for (int i = 0; i < phoneList.size(); i++) {
Smartphone phone = phoneList.get(i);
if (phone.getBrand().equalsIgnoreCase("Nokia")) {
nokiaList.add(phone);
}
if (phone.getBrand().equalsIgnoreCase("Samsung")) {
if (phone.getModel().equalsIgnoreCase("Galaxy Y")) {
countSamsung++;
}
}
}

Is it possible to use 2 Data Type in an Custom ADT(Sorted Linked List)?

I am trying to do a Leaderboard for a game by using a Sorted Linked List. I was able to do so by sorting the point in descending order which mean higher point to lower point. Moreover, I will also need to put player name together with the point. The problem comes here. The SLL(Sorted Linked List) I implemented is an Integer data type, it works perfectly with the Integer data type as it sorted the numbers.
SortedListInterface<Integer> Player = new LeaderboardSortedLinkedList<Integer>();
But when I trying to put the player name which used String, it won't be able to do so because the point data type will need to follow the player name's data type.
Below are the codes of the driver class:
public class testLeaderboard {
public static void main(String[] args) {
SortedListInterface<Integer> Player = new LeaderboardSortedLinkedList<Integer>();
Player.add(1000000);
Player.add(500000);
Player.add(250000);
Player.add(125000);
Player.add(64000);
Player.add(32000);
Player.add(16000);
Player.add(8000);
Player.add(4000);
Player.add(2000);
Player.add(1000);
Player.add(500);
Player.add(300);
Player.add(200);
Player.add(100);
System.out.printf("=================================\n"
+ " Leaderboard\n"
+"=================================\n");
for(int i=0; i< Player.size();i++){
System.out.printf("%3d. %s\n",(i+1), Player.get(i+1));
}
}
}
Here is the Entity class
public class Player {
private String name;
private int prize;
public Player(String name, int prize) {
this.name = name;
this.prize = prize;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrize() {
return prize;
}
public void setPrize(int prize) {
this.prize = prize;
}
#Override
public String toString() {
return "Player{" + "name=" + name + ", prize=" + prize + '}';
}
}
Here's the custom Sorted Lineked List
public class LeaderboardSortedLinkedList<T extends Comparable<T>> implements SortedListInterface<T> {
private Node firstNode;
private int length;
public LeaderboardSortedLinkedList() {
firstNode = null;
length = 0;
}
public boolean add(T newEntry) {
Node newNode = new Node(newEntry);
Node nodeBefore = null;
Node currentNode = firstNode;
while (currentNode != null && newEntry.compareTo(currentNode.data) < 0) {
nodeBefore = currentNode;
currentNode = currentNode.next;
}
if (isEmpty() || (nodeBefore == null)) { // CASE 1: add at beginning
newNode.next = firstNode;
firstNode = newNode;
} else { // CASE 2: add in the middle or at the end, i.e. after nodeBefore
newNode.next = currentNode;
nodeBefore.next = newNode;
}
length++;
return true;
}
public boolean contains(T anEntry) {
boolean found = false;
Node tempNode = firstNode;
int pos = 1;
while (!found && (tempNode != null)) {
if (anEntry.compareTo(tempNode.data) <= 0) {
found = true;
} else {
tempNode = tempNode.next;
pos++;
}
}
if (tempNode != null && tempNode.data.equals(anEntry)) {
return true;
} else {
return false;
}
}
public int size(){
int count = 0;
//Node current will point to head
Node current = firstNode;
while(current != null) {
//Increment the count by 1 for each node
count++;
current = current.next;
}
return count;
}
public T get(int position){
T result = null;
if ((position >= 1) && (position <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < position - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}
public final void clear() {
firstNode = null;
length = 0;
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return (length == 0);
}
public String toString() {
String outputStr = "";
Node currentNode = firstNode;
while (currentNode != null) {
outputStr += currentNode.data + "\n";;
currentNode = currentNode.next;
}
return outputStr;
}
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
next = null;
}
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}
And the results is here
=================================
Leaderboard
=================================
1. 1000000
2. 500000
3. 250000
4. 125000
5. 64000
6. 32000
7. 16000
8. 8000
9. 4000
10. 2000
11. 1000
12. 500
13. 300
14. 200
15. 100
Here's my testing on the point with string data type because I can't think a way to use player name and point with 2 different data types at the same time in my custom ADT.
public class testLeaderboard {
public static void main(String[] args) {
SortedListInterface<String> Player = new LeaderboardSortedLinkedList<String>()
Player.add("1000000");
Player.add("500000");
Player.add("250000");
Player.add("125000");
Player.add("64000");
Player.add("32000");
Player.add("16000");
Player.add("8000");
Player.add("4000");
Player.add("2000");
Player.add("1000");
Player.add("500");
Player.add("300");
Player.add("200");
Player.add("100");
System.out.println(Player);
}
And here's the result that it compare the first letter of the string.
8000
64000
500000
500
4000
32000
300
250000
2000
200
16000
125000
1000000
1000
100
Is there anyway to use both String and Integer in one ADT because if i couldn't do so, I won't be able sort the point. I'm so sorry for the long question. I am very new to data structures and algorithms so I really need some help on this. Much appreciate.
To keep the points and names together, you need to add Player objects into the list as they are, not just their points or their names:
SortedListInterface<Player> players = new LeaderboardSortedLinkedList<>();
players.add(new Player("Alpha", 1000000));
players.add(new Player("Beta", 500000));
players.add(new Player("Gamma", 250000));
For this to work, you will need to be able to compare Player objects by their point numbers. You do that by implementing the Comparable interface and adding a compareTo method.
You'll also want to add a toString() method, so that you can print a Player object.
public class Player implements Comparable<Player> {
private String name;
private int prize;
#Override
public int compareTo(Player other) {
return Integer.compare(this.prize, other.prize);
}
#Override
public String toString() {
return String.format("name='%s' prize=%d", name, prize);
}
}
Thank You for helping me I successfully get the output I want. But got a little problem which is this
=================================
Leaderboard
=================================
1. name='Alpha' prize=1000000
2. name='Beta' prize=500000
3. name='Gamma' prize=250000
BUILD SUCCESSFUL (total time: 1 second)
It print the output at this way [name="Alpha"]. Im not sure what is the problem but i guess it's my System.out.print code.
System.out.printf("%3d. %s\n",(i+1), players.get(i+1));
and here's my .get() function.
public T get(int position){
T result = null;
if ((position >= 1) && (position <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < position - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}

Sorting a Linked List in alphabetical order

I have an assignment where I have to make my one linked list that holds a person name and their vehicle plate number that enters in a compound. but I need to sort the list in alphabetical order by using the license plate number(example: ABS1234). I have been doing some research on sorting for example merge sort or using the collection.sort, but can't wrap my head around it. it will be awesome if I can get a little push on how to do this. Thanks in advance.
public class Node {
//data fields
public String regPlate; // Registration Plate
public String firstName;
public String lastName;
//refrence link
public Node link;
//default constructor
public Node()
{
regPlate = "";
firstName = "";
lastName = "";
}//end of constructor.
}//end of node class
this is the Node class that i created.
public class LinkedList {
Node head;
Node tail;
Node current;
int listLength;
Scanner input = new Scanner(System.in);
//default constructor
public LinkedList ()
{
head = null;
listLength = 0;
}
//inserting new node in the beginning of the list
public void insertFirst(String fN, String lN, String rP)
{
Node newNode = new Node();
newNode.firstName = fN;
newNode.lastName = lN;
newNode.regPlate = rP;
//make newNode point to the first node in the life
newNode.link = head;
//makes head point to the new first node
head = newNode;
if(head == null)
tail = newNode;
++listLength;
}//end of insertFirst
public void displayDataLog()
{
Node current;
current = head;
while(current != null)
{
System.out.print("\n FullName: " + current.firstName + " " + current.lastName +
"\n Registration Plate Number: " + current.regPlate);
current = current.link;
}
}//end of display vehicles
public void totalVehicles()
{
System.out.print("\n Total Vehicle on the campus: " + listLength);
}//end of total vehicles
}//end of linked list
Using Collection.sort() this should be fairly easy.
First, you need to create your own Comparator, since the default one won't work (you want to order by a specific field, the license plate).
class NodeComparator implements Comparator<Node> {
#Override
public int compare(Node n1, Node n2) {
return n1.regPlate.compareTo(n2.regPlate);
}
}
Now you have your Comparator, just use it, here is an example I used (created an ArrayList and introduced every element of the list there):
private static LinkedList sortList(LinkedList list) {
// I use an ArrayList so I can just use Collections.sort
LinkedList sortedList = new LinkedList();
Node current = list.head;
ArrayList<Node> array = new ArrayList<Node>();
while (current != null) {
array.add(current);
current = current.link;
}
array.sort(new NodeComparator());
for (int i = array.size()-1; i >= 0; i--) {
sortedList.insertFirst(array.get(i));
}
return sortedList;
}
I made a few changes that will, most likely, be easy to adapt to your own program. You can see the full working program here: https://code.sololearn.com/cgzN5sQOI8uW.
The entire the code, for the sake of completion (and just in case the link stops working):
import java.util.*;
import java.lang.*;
import java.io.*;
class Playground {
public static void main(String[ ] args) {
LinkedList list = new LinkedList();
list.insertFirst("Robert", "Rodriguez", "RB123");
list.insertFirst("Andrew", "Andrews", "AB123");
list.insertFirst("Thomas", "Thomson", "TB123");
System.out.println(list); // Prints unordered list, opposite order as they were introduced, since they were introduced from the beggining of the list.
LinkedList sorted = sortList(list);
System.out.println("\n"+sorted);
}
private static LinkedList sortList(LinkedList list) {
// I use an ArrayList so I can just use Collections.sort
LinkedList sortedList = new LinkedList();
Node current = list.head;
ArrayList<Node> array = new ArrayList<Node>();
while (current != null) {
array.add(current);
current = current.link;
}
System.out.println("\nTemp Array:");
System.out.println(array);
array.sort(new NodeComparator());
System.out.println("\nTemp Array (now sorted):");
System.out.println(array);
for (int i = array.size()-1; i >= 0; i--) {
sortedList.insertFirst(array.get(i));
}
return sortedList;
}
}
class NodeComparator implements Comparator<Node> {
#Override
public int compare(Node n1, Node n2) {
return n1.regPlate.compareTo(n2.regPlate);
}
}
class Node {
//data fields
public String regPlate; // Registration Plate
public String firstName;
public String lastName;
//refrence link
public Node link;
//default constructor
public Node()
{
regPlate = "";
firstName = "";
lastName = "";
}//end of constructor.
public String toString() {
return this.regPlate;
}
}//end of node class
class LinkedList {
Node head;
Node tail;
Node current;
int listLength;
//default constructor
public LinkedList ()
{
head = null;
listLength = 0;
}
//inserting new node in the beginning of the list
public void insertFirst(String fN, String lN, String rP)
{
Node newNode = new Node();
newNode.firstName = fN;
newNode.lastName = lN;
newNode.regPlate = rP;
insertFirst(newNode);
}//end of insertFirst
public void insertFirst(Node newNode) {
//make newNode point to the first node in the life
newNode.link = head;
//makes head point to the new first node
head = newNode;
if(head.link == null)
tail = newNode;
++listLength;
}
public void displayDataLog()
{
Node current;
current = head;
while(current != null)
{
System.out.print("\n FullName: " + current.firstName + " " + current.lastName +
"\n Registration Plate Number: " + current.regPlate);
current = current.link;
}
}//end of display vehicles
public void totalVehicles()
{
System.out.print("\n Total Vehicle on the campus: " + listLength);
}//end of total vehicles
public String toString() {
String str = "List:\nhead -> [ ";
Node current = head;
while (current != null) {
str = str + current + (current == tail ? " ] <- tail" : ", ");
current = current.link;
}
return str;
}
}//end of linked list

How to display a string in linked list using nodes

I created a basic node linked list that displays the size of the list in number (ie: 0 - 9 )
Now I'm trying to alter what i have to display a list of names. I'm confused on what I need to change and what is going to be different. The names are going to be in string format. Eventually I'm going to read in a list of names from a txt file. For now I'm using just 3 names and test data.
import java.util.*;
public class Node {
public int dataitems;
public Node next;
Node front;
public void initList(){
front = null;
}
public Node makeNode(int number){
Node newNode;
newNode = new Node();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(Node front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public Node findTail(Node front) {
Node current;
current = front;
while(current.next != null){
//System.out.print(current.dataitems);
current = current.next;
} //System.out.println(current.dataitems);
return current;
}
public void addNode(Node front ,int number){
Node tail;
if(isListEmpty(front)){
this.front = makeNode(number);
}
else {
tail = findTail(front);
tail.next = makeNode(number);
}
}
public void printNodes(int len){
int j;
for (j = 0; j < len; j++){
addNode(front, j);
} showList(front);
}
public void showList(Node front){
Node current;
current = front;
while ( current.next != null){
System.out.print(current.dataitems + " ");
current = current.next;
}
System.out.println(current.dataitems);
}
public static void main(String[] args) {
String[] names = {"Billy Joe", "Sally Hill", "Mike Tolly"}; // Trying to print theses names..Possibly in alphabetical order
Node x = new Node();
Scanner in = new Scanner(System.in);
System.out.println("What size list? Enter Number: ");
int number = in.nextInt();
x.printNodes(number);
}
}
several things must be changed in my opinion
public void printNodes(String[] nameList){
int j;
for (j = 0; j < nameList.length; j++){
addNode(front, nameList[j]);
} showList(front);
}
you have to pass the array containing the names
x.printNodes(names);
also change:
public void addNode(Node front ,String name){
Node tail;
if(isListEmpty(front)){
this.front = makeNode(name);
}
else {
tail = findTail(front);
tail.next = makeNode(name);
}
}
and :
public Node makeNode(String name){
Node newNode;
newNode = new Node();
newNode.dataitems = name;
newNode.next = null;
return newNode;
}
and don't forget to change the type of dateitem into string :
import java.util.*;
public class Node {
public String dataitems;

Categories