Another issue with LinkedList implementation with another class - java

Employee Class:
public class Employee
{
String ID;
String Fname;
String Lname;
String City;
String Major;
int GPA;
public Employee()
{
GPA = 0;
}
public void ShowInfo()
{
JOptionPane.showMessageDialog(null, "ID: " + ID + "\nFirst Name: " + Fname + "\nLast Name:" + Lname + "\nCity: " + City + "\nMajor: " + Major + "\nGPA: " + GPA);
}
public void EnterInfo()
{
ID = JOptionPane.showInputDialog("Enter Student ID");
Fname = JOptionPane.showInputDialog("Enter Student First Name");
Lname = JOptionPane.showInputDialog("Enter Student Last Name");
City = JOptionPane.showInputDialog("Enter Student City");
Major = JOptionPane.showInputDialog("Enter Student Major");
String gpa = JOptionPane.showInputDialog("Enter Student GPA");
GPA = Integer.parseInt(gpa);
}
}
}
Linked List:
public class EmployeeList
{
Node first;
Node last;
int count;
public EmployeeList()
{
first = new Node();
first = null;
last = new Node();
last = null;
count = 0;
}
public boolean empty()
{
return first == null;
}
public void add(Employee emp)
{
Node newEmployee = new Node();
newEmployee.e = emp;
newEmployee.e.EnterInfo();
newEmployee.next=null;
if(empty())
{
first=newEmployee;
last=first;
}
else
{
last.next = newEmployee;
last = last.next;
}
count++;
}
public boolean search(String id)
{
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
emp.ShowInfo();
return true;
}
temp=temp.next;
}
return false;
}
public boolean delete(String id)
{
Employee emp = new Employee();
if(!empty())
{
if(first.e.ID.equals(id))
{
first=first.next;
return true;
}
else
{
Node previous = new Node();
Node temp = new Node();
previous = first;
temp = first.next;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
count--;
previous.next = temp.next;
return true;
}
previous = previous.next;
temp = temp.next;
}
return false;
}
}
return false;
}
public String ALL()
{
String all = new String();
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
all = all + emp.ID + "-";
temp = temp.next;
}
all = all + "null";
return all;
}
}
I really don't know what's the problem here, If i try to print them all, i keep getting the last entered value.
Node class:
public class Node
{
Employee e = new Employee();
Node next;
}
By searching im not getting any result, just employee ID not found.
EnterInfo method is just for input of the variables (ID,Fname.....)
Any help ? and thanks.
Edit: i know its wrong that way, i should add getters and setter, but this is how the teacher started and told us to start this way.

Your search is failing because you are incorrectly testing for String equality. This line:
if(emp.ID == id)
Tests for object reference equality. It will only work for interned values (which is out of scope for this assignment of yours). You should change it too:
if(id.equals(emp.ID))
Some quick notes on your code:
You are not following best practices in naming. Your variables should
begin with lowercase letters.
You are not following best practice in property scoping. Your class
variables should be private, with appropriate getters/setters
In the beginning of your search method you are unnecessarily creating
a Node instance
Node temp = new Node();
Your are incorrectly testing for String equality in your delete
method.

Related

Java: Linked list node isn't working in my code

So I am very very at linked list and creating nodes is very confusing. for my program, I have to create a method in main class called insertAfter(TrackerNode nodeLoc) that refers to another class I have created for inserting data in node. The user inputs are initially, a total number of nodes, then data for each node (name and age).
There are a few issues with your code as posted, the age field (according to your requested output) should be an int and you need to remember which order you declare age and name in your constructors. It is also possible to shorten the repetitive constructors with this(); and I would prefer using toString() over a custom data dumper method. Like,
public class TrackerNode {
private int age;
private String name;
private TrackerNode nextNodeRef; // Reference to the next node
public TrackerNode() {
this("", 0);
}
public TrackerNode(String name, int age) {
this(name, age, null);
}
public TrackerNode(String name, int age, TrackerNode nextLoc) {
this.age = age;
this.name = name;
this.nextNodeRef = nextLoc;
}
public void insertAfter(TrackerNode nodeLoc) {
TrackerNode tmpNext = this.nextNodeRef;
this.nextNodeRef = nodeLoc;
nodeLoc.nextNodeRef = tmpNext;
}
// Get location pointed by nextNodeRef
public TrackerNode getNext() {
return this.nextNodeRef;
}
#Override
public String toString() {
return String.format("%s, %d", this.name, this.age);
}
}
Then your main loop should actually use the i you read and you need to reset to the head node before you print. Something like,
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// References for TrackerNode objects
TrackerNode headNode = null, currNode = null, lastNode = null;
// Scan the number of nodes
int i = scnr.nextInt();
// in data and insert into the linked list
for (int k = 0; k < i; k++) {
String name = scnr.next();
int age = scnr.nextInt();
scnr.nextLine();
if (lastNode != null) {
currNode = new TrackerNode(name, age);
lastNode.insertAfter(currNode);
} else {
currNode = headNode = new TrackerNode(name, age);
}
lastNode = currNode;
}
// Print linked list
currNode = headNode;
while (currNode != null) {
System.out.println(currNode);
currNode = currNode.getNext();
}
}
Which I tested with your provided input (and the output I received seems to match the posted expectations):
3
John
22
Silver
24
Smith
21
John, 22
Silver, 24
Smith, 21

how to remove and search an object by name from linked list in java

I can write the function to delete at position I choose. But I have problems when I write the function to delete the employee by input of the employee's name. I still have the same problem with the search function. Use case 7, 8 in menu to perform delete and search function. Can anybody help me with my code?
Here's my source code:
import java.util.Scanner;
import java.io.Serializable;
/* Class Node */
class Employee implements Serializable{
int ID;
String name;
String address;
Employee(int emp_ID, String emp_name, String emp_address){
ID = emp_ID;
name = emp_name;
address = emp_address;
}
public void print(){
System.out.println(ID);
System.out.println(name);
System.out.println(address);
}
#Override
public String toString() {
return ID + "-" + name + "-" + address;
}
}
class Node
{
protected Employee emp;
protected Node link;
public Object name;
public Node in;
/* Constructor */
public Node()
{
link = null;
emp = null;
}
/* Constructor */
public Node(Employee e,Node n)
{
emp = e;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(Employee e)
{
emp = e;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public Employee getData()
{
emp.print();
return null;
}
}
/* Class linkedList */
class linkedList
{
protected Node start ;
protected Node end ;
public int size ;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of the list */
public int getSize()
{
return size;
}
/* Function to insert element at the begining */
public void insertAtStart(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Employee e , int pos)
{
Node nptr = new Node(e,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void searchByName(){
}
public void deleteByName(){
}
public void deleteAtPos(int pos)
{
if (size == 1 && pos == 1)
{
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1)
{
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
/* Function to display contents */
public void display()
{
System.out.print("\nEmployee Management= ");
Node ptr = start;
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == start)
{
System.out.print(start.getData()+ "\n");
return;
}
System.out.print(start.getData()+ "" + "\n");
ptr = start.getLink();
while (ptr.getLink() != start)
{
System.out.print(ptr.getData()+ "" + "\n");
ptr = ptr.getLink();
}
System.out.print(ptr.getData()+ "\n");
}
}
/* Class CircularSinglyLinkedList */
public class CurrilarLinkedList
{
public static void main(String[] args)
{
int ID = 0;
String name = null;
String address = null;
Employee emp = null;
Scanner scan = new Scanner(System.in);
/* Creating object of linkedList */
linkedList list = new linkedList();
System.out.println("Circular Singly Linked List Test\n");
char ch;
/* Perform list operations */
do
{
System.out.println("\nCircular Singly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
System.out.println("7. delete by name");
System.out.println("8. search by name");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.print("Please input an Employee \n");
Scanner myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtStart(emp);
break;
case 2 :
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtEnd(emp);
break;
case 3 :
System.out.println("Enter position");
int pos = scan.nextInt() ;
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(emp, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
list.isEmpty();
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
case 7:
System.out.println("Enter the name of employee you want to delete:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
case 8:
System.out.println("Enter the name of employee you want to search:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display List */
list.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

How Do I Process objects in my custom linked list?

I successfully made a linked list, but now I am having trouble processing it. What methods do I need to add to my FoodList class to be able to process my objects? For example, I need to have the user be able to choose to manually add food objects together so I can print a meal. Also, I can't use any collections classes from the java API. It all must be custom.
public static void main(String[] args) {
FoodList list = new FoodList();
boolean keepGoing = true;
int scanResultInt;
try
{
//I/O stream
FileReader fr = new FileReader("foodlist.txt");
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
Food hold = new Food();
while(scan.hasNext()){
list.add(hold = new Food());
String str = scan.next();
//str = scan.next();
hold.setName(str);
str = scan.next();
hold.setGroup(str);
int cal = scan.nextInt();
hold.setNumCal(cal);
double percent = scan.nextDouble();
hold.setPercentDV(percent);
list.add(hold);
}
//System.out.println("" + list.toString());
br.close(); //close I/O stream
}
catch(IOException e){
System.err.println("I/O EXCEPTION: " + e.getMessage());
}
Scanner scan2 = new Scanner(System.in);
do {
System.out.println("---------------------------------------------------------");
System.out.println(" Welcome to the Parkland Meal Selector" );
System.out.println("---------------------------------------------------------");
System.out.println("Enter the number of the menu option you would like to select:");
System.out.println(" 1) List food database");
System.out.println(" 2) Create meal by manual selection");
System.out.println(" 3) Create meal by random selection");
System.out.println(" 4) Remove foods high in calories");
System.out.println(" 5) Exit");
scanResultInt = scan2.nextInt();
switch(scanResultInt) {
case 1: {
System.out.println("" + list.toString());
break;
}
case 2: {
System.out.println("Create-A-Meal Menu\n");
System.out.println("Enter the name of a food you would like to add:\n");
String foodWanted = scan2.next();
/*while( != null){
if(foodWanted.equals());
}*/
/*Food tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;*/
}
case 3: {
System.out.println("Create meal by random selection: \n");
break;
}
case 4: {
System.out.println("Remove Food High In Calories: \n");
break;
}
case 5: {
keepGoing = false;
break;
}
}
}
while(keepGoing);
}
Here is my Linked List:
public class FoodList {
// Class fields
private FoodNode head;
private int listCount;
// Private inner class
private class FoodNode
{
public Food f;
public FoodNode next;
public FoodNode(Food f)
{
this.f = f;
this.next = null;
}
}
// Constructor for LinkedList
public FoodList()
{
// Initialize start of the list
head = null;
listCount = 0;
}
// Add method (adds a reservation to the linked list)
public void add(Food f)
{
// Create a new ReservationNode
FoodNode node = new FoodNode(f);
// If this is the first node
if( head == null )
head = node;
else
{
FoodNode tmp = head;
while(tmp.next != null)
tmp = tmp.next;
tmp.next = node;
}
listCount++
}
/*public boolean hasThatFood(String food){
boolean haveThat = false;
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
if (food == f.getName());
haveThat = true;
}
return haveThat;
}*/
/*public boolean hasNext(){
boolean hasNext = false;
if(head != null) {
hasNext = true;
return hasNext;
}
}*/
#Override
public String toString() {
String result = "My Foods:" + '\n';
// Loop through all the reservation nodes
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;
}
}
And my Food class
public class Food {
private String name;
private String group;
private int numCal;
private double percentDV;
public Food() {//String name, String group, int numCal, double percentDV
/*this.name = name;
this.group = group;
this.numCal = numCal;
this.percentDV = percentDV;*/
name = "";
group = "";
numCal = 0;
percentDV = 0.0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getNumCal() {
return numCal;
}
public void setNumCal(int numCal) {
this.numCal = numCal;
}
public double getPercentDV() {
return percentDV;
}
public void setPercentDV(double percentDV) {
this.percentDV = percentDV;
}
#Override
public String toString() {
return "Food{" +
"name: '" + name + '\'' +
", Food Group: '" + group + '\'' +
", Calories: " + numCal +
", Daily Percent: " + percentDV +
'}';
}
}
I know this is spaghetti code, but this is my last resort. Any help would be appriciated!
To operate on the objects you have to write your custom Iterator. I guess here is nothing criminal to open LinkedList source and look how it works.
Something like this, You can find many resource online,
https://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
Here is one.
public Object getElement(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
You have implemented some complicated classes. Inner logic of its is not very clear like your issue. So almost any answer will not cover your needs.
If I would you I would try recommend the logic using java core tools (without implementing classes, that implemented in best way LinkedList, ArrayList...). Logic should be converted into some structural solution. For example:
enter point creates and calls your stream service to handle provided input stream;
stream handler should manipulate builder;
builder result have to be collected into composite;
and so on...
If you provide your logic in more structural way you would ask more clear question pointing the issue. Also I believe your question will disappear after this preparation.
Also I would recommend you to get familiar with next GoF patterns: builder, factory method, composite, strategy.

How to Instantiate Connection between Student Class and my LinkedList<E>. Wont grab E.getElement()

I'm working on creating my own LinkedList. My L.L. worked 100% when running simple I/O from command line, but now I have to implement it into my Student class. It adds a Student, displays a student, won't remove Student # Node, in-fact, it won't even read THE ONLY student in the list! All BlueJ tells me is this:
Error(s) found in class
It's some kind of connection logic and for two days I have tried everything I can think of.
Here is my Student, removeStudent(), Class Node, and LinkedList
public class Node
{
private Student item;
private Node node;
private int thisIdx;
private String fullName,firstName,lastName,gender,major,netId;
private int uin,age;
private double gpa;
public Node()
{
this(null,null);
}
public Node(Student stu,Node node)
{
this.item = stu;
this.setNext(node);
thisIdx = totalCount() - 1;
this.setNodeIndex(thisIdx);
}
public int getIndex()
{
return this.thisIdx;
}
public void setNodeIndex(int idx)
{
thisIdx = idx;
}
public void setNext(Node n1)
{
node = n1;
}
public Node getNext()
{
return node;
}
public boolean isEmpty()
{
return ( this == null);
}
public Student display()
{
return this.item;
}
public void setItem(Links data)
{
this.item = data;
}
public Student getItem()
{
return item;
}
}
public class Links<E>
{
private Node start,tail,next;
private int size=0; private int idx; private String item;
private Student student;
/**
* Constructor for objects of class MyLList
*/
public Links()
{
start = new Node();
}
public void addLink(E object)
{
tail = start;
start = new Node(object,tail);
size++;
}
public int totalCount()
{
return size;
}
public Node get(Node node)
{
return node;
}
public void set(Node node)
{
node.setNext(node.getNext());
}
public String emptyMessage()
{
String message = "Your student is not in the student files.\n\n";
return message;
}
public Node getStart()
{
Node curr = start;
return curr;
}
public void clear()
{
Node start = new Node();
size = 0;
}
public void removeLink(Node node) throws NullPointerException
{
try{
Node del,curr,next,prev;
prev = start; curr = start;
while ( curr != node )
{
if ( curr.getNext() == null)
{
throw new NullPointerException();
}else
{
prev = curr;
curr = curr.getNext();
}
}
if ( curr == start)
{
start = start.getNext();
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
}
}catch (NullPointerException npe)
{
Lab_12.viewer.append("Breaking in Links" + "\n\n");
}
}
public void sort()
{
Node curr,next,temp,prev;
prev = start;
curr = start;
next = start.getNext();
int move;
Student[] copyToThis = new Student[this.size];
if (this.totalCount() > 1)
{
//copy contents of linked list to array
for (int i=0; i < this.totalCount(); i++)
{
if ( !curr.isEmpty() )
{
Student copyItem = curr.getItem();
copyToThis[i] = copyItem;
prev = curr;
if ( curr.getNext() != null)
{
curr = curr.getNext();
}else
{
prev.setNext(curr.getNext());
}
}
for (int k=0; k < copyToThis.length-1;k++)
{
int tempIdx = k;
if ( copyToThis[k] == null )
{
copyToThis[tempIdx] = copyToThis[k];
while ( k < copyToThis.length-1 )
{
copyToThis[k] = copyToThis[k+1];
copyToThis[k+1] = copyToThis[tempIdx];
tempIdx = k;
k++;
}
}
}
}
//sort array in reverse order -----> LinkedList is FIFO structure
for (int i =0; i < copyToThis.length; i++)
{
Student first = copyToThis[i];
Student tempObject = copyToThis[i];
int tempIndex = i;
for (int k=i; k < copyToThis.length; k++)
{
if (copyToThis[k] != null)
{
move = copyToThis[k].getFullName().compareToIgnoreCase(first.getFullName());
if (move > 0)
{
first = copyToThis[k];
tempIndex = k;
}
}else
{
break;
}
}
if (first == null )
{
break;
}else
{
move = first.getFullName().compareToIgnoreCase(tempObject.getFullName());
if (move > 0 )
{
copyToThis[i] = first;
copyToThis[tempIndex] = tempObject;
tempIndex = i;
}
}
}
//clear list before setting in alphabetical order -----> if not cleared, list will append not replace
this.clear();
for (int i=0; i < copyToThis.length; i++)
{
if ( copyToThis[i] != null)
{
this.addLink(copyToThis[i]);
}
}
}
//test print of array
/*for (int i=0; i < copyToThis.length; i++)
{
Lab_12.viewer.append(i + ") " + copyToThis[i]);
}*/
}
public String displayFirst()
{
Node first = start;
String showFirst = first.getItem().toString();
return showFirst;
}
public void display()
{
String showThisView;
Node prev,curr,next;
prev = start; curr = prev; next = start.getNext();
for (int i=0; i < this.totalCount();i++)
{
if (!curr.isEmpty())
{
showThisView = curr.getItem().toString();
Lab_12.viewer.append(showThisView + "\n\n");
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
next = next.getNext();
}
prev = next;
curr = prev;
if (prev.getNext() != null)
{
next = prev.getNext();
}else
{
break;
}
}
}
public String search(String data) throws NullPointerException
{
try{
Node p = start;
while(p!=null)
{
if ( !p.getItem().equals(data) )
{
p = p.getNext();
}else
{
return data;
}
}
}catch (NullPointerException npe)
{
System.out.println("Your item is not in the list\n");
}
}
}
public void removeStudent(Links<Student> studentLinks1)
{
try
{
String toRemove;
int choice;
int counter =0;
toRemove = JOptionPane.showInputDialog(null,"Enter the student last name to be removed:");
String find;
int uin;
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()) )
{
if ( studentLinks1.get(i).getFullName().equalsIgnoreCase(toRemove) )
{
counter++;
}
}
if (counter > 1)
{
viewer.append("You have more than one student with the last name, " + toRemove + ".\n\n");
viewer.append("Students with last name: " + toRemove + "\n\n");
/*
* create array to hold current matching indexes;
*/
for (Node i=studentLinks1.getStart(); i.getNext() !=null; i.setNext(i.getNext()))
{
find = studentLinks1.get(i).getLastName().toString();
if ( studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
uin = studentLinks1.get(i).getUin();
viewer.append("Name: " + studentLinks1.get(i).getFullName().toString() +
"\n\tUIN: " + uin + "\n\n");
}
}
/*
* Get user input for student removal & remove student
*/
int match = 0;
choice = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the UIN of the student you wish to remove: "));
for (Node i=studentLinks1.getStart(); i.getNext() !=null ; i.setNext(i.getNext()))
{
uin = studentLinks1.get(i).getUin();
if ( choice != uin)
{
match++;
}
if (match == Links.totalCount() )
{
throw new InputMismatchException();
}
}
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i).getUin() == choice )
{
String name = studentLinks1.get(i).getFullName().toString();
viewer.append(name + " " + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
Student.getStudentCount();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
if ( counter == 1)
{
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i) != null && studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
String firstName = studentLinks1.get(i).getFirstName().toString();
String lastName = studentLinks1.get(i).getLastName().toString();
viewer.append(firstName + " " + lastName + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
}else
{
viewer.append(studentLinks1.emptyMessage());
}
}
}catch (InputMismatchException ime )
{
viewer.append("You entered an incorrect student id.\nPlease re-enter the student id.");
throw ime;
}
}
As you can see in my removeStudent(), I have formatted the for loops to iterate through the L.L. with the nodes themselves. If in LL class, I can perform node.getElement() with results, then why will that not work in my main in Student? I have tried
studentLinks1.get(I).getItem().getElement();
studentLinks1.get(i.getElement())
I am seriously at a loss with this one. Any help is much appreciated!

Sorting singly linked list by second node element. Java

I am trying to get a way to sort this singly linked list by the last names that have been entered into it. I thought I might try a bubble sort but I am having problems traversing the list by the second element and comparing. The list contains only 3 names right now as console entries but it should have 10 names when I am done. Any help would be greatly appreciated.
package LinkedList;
import java.util.*;
class SLinkedList
{
public String data1;
public String data2;
public SLinkedList next;
public SLinkedList()
{
data1 = "";
data2 = "";
next = null;
}
public SLinkedList(String value1, String value2)
{
data1 = value1;
data2 = value2;
next = null;
}
public SLinkedList InsertNext(String value1, String value2)
{
SLinkedList node = new SLinkedList(value1, value2);
if(this.next == null)
{
// Easy to handle
node.next = null; // already set in constructor
this.next = node;
}
else
{
// Insert in the middle
SLinkedList temp = this.next;
node.next = temp;
this.next = node;
}
return node;
}
public int DeleteNext()
{
if(next == null)
return 0;
SLinkedList node = this.next;
this.next = this.next.next; // can be NULL here
node = null;
return 1;
}
public void Traverse(SLinkedList node)
{
if(node == null)
node = this;
System.out.println("\nTraversing in Forward Direction\n");
while(node != null)
{
System.out.println(node.data1 + " " + node.data2);
node = node.next;
}
}
public void bubbleSort(SLinkedList node) {
if(node == null)
node = this;
String current;
String second;
String temp;
System.out.println("Attemptint to sort...");
while(node != null)
{
current = node.data2;
node = node.next;
second = node.data2;
System.out.println(current + " " + second);
if(current.compareTo(second) < 0) {
System.out.println("greater than zero");
}
node = null;
//node = node.next;
}
}
public static void main(String[] args)
{
String firstName;
String lastName;
Scanner sc = new Scanner(System.in);
System.out.print("Enter names in the format of: 'Ed King' with"
+ " a single space in between.");
firstName = sc.next();
lastName = sc.next();
SLinkedList node1 = new SLinkedList(firstName, lastName);
System.out.print("Enter second name: ");
firstName = sc.next();
lastName = sc.next();
SLinkedList node2 = node1.InsertNext(firstName, lastName);
System.out.print("Enter third name: ");
firstName = sc.next();
lastName = sc.next();
SLinkedList node3 = node2.InsertNext(firstName, lastName);
node1.bubbleSort(null);
}
}
Hints:
Your implementation of bubble sort is fundamentally wrong. Bubble sort requires a nested loop.
Given the way you've designed the data structure, the bubble sort method has to return the new start of list.
Don't start method names with a capital letter. This is Java not C#.
If you can't visualize what your code is doing, use a debugger to single-step it and observe how the state changes.
First of all Linkedlist should be sorted using merge sort. So chage your algo.
Coming to bubble sort implementation , your implementation is not correct[why are you not using temp at all]. You shld look to swap nodes.

Categories

Resources