Selection sort in linked list java - java

My program is not sorting the list and I can't figure out the problem.
The list is the same before sorting and after sorting.
public void SelectionSort(){
for (Node index = head; ((index != null)&&(index.getnext()!=null)); index = index.getnext()) {
Node min = index;
for (Node test = min.getnext(); test != null; test = test.getnext()) {
if (test.getAcc().compareTo(min.getAcc()) < 0){
min = test;
}
}
if(index!=min){
Node temp = new Node();
temp=index;
index=min;
min =temp;
}
}
}
Below is my class Node:
public class Node {
private int ID;
private String Acc;
private String Symbol;
private String Function;
private String UniGene;
private String Chromosome;
private Node next;
public Node(){
}
public Node(int id, String acc,String unigene, String symbol, String chromosome, String function){
ID=id;
Acc=acc;
Symbol=symbol;
UniGene = unigene;
Chromosome = chromosome;
Function=function;
}
public void displayNode() // display
{
System.out.print("{"+ID+","+Acc+","+Symbol+","+Function+"} \n");
}
int getID(){
return ID;
}
String getAcc(){
return Acc;
}
String getUniGene(){
return UniGene;
}
String getSymbol(){
return Symbol;
}
String getChromosome(){
return Chromosome;
}
String getFunction(){
return Function;
}
void setnext(Node newnode)
{
next = newnode;
}
Node getnext()
{
return next;
}
}

I think that the problem is that you need to take care of the next pointer when you move nodes. In your original code you just swap 2 references, but you don't change the order in the list:
Node next = min.getnext();
min.setnext(index);
index.setnext(next);
This won't work directly, but the problem lies there. You'll need to save the "previous" node, and set previous.setnext(index) or something like that.
BTW:
Node temp = new Node();
temp=index;
You create a new Node, but you don't use it, 'cause in the next line you assign index to temp.
Node temp = index;

Related

compareTo with generic linkedList

I am new to java and i have encountered a problem while making a generic class with comparable interface. In the sortedInsert method of LinkedList class it gives error on head.value.compareTo(new_node.value), i am making an object of Linkedlist class in main so , according to my understanding head.value should give me an employee object for which i am calling compareTo . but still it gives me this error . is there anything i understood incorrectly ? or making a mistake in this code .
cannot find symbol
symbol: method compareTo(T)
public class Employee implements Comparable<Employee>
{
private int empID;
private String name;
private int salary;
private boolean manager;
private int subordinates;
public Employee()
{
empID = 0;
name = "";
salary = 0;
manager = false;
subordinates = 0;
}
public Employee(int id , String name , int salary , boolean manager , int sub)
{
empID = id;
this.name = name;
this.salary = salary;
this.manager = manager;
subordinates = sub;
}
public int GetID()
{
return this.empID;
}
public String GetName()
{
return this.name;
}
#Override
public int compareTo(Employee other)
{
if (this.empID < other.empID)
{
return -1;
}
else if (this.empID > other.empID)
{
return 1;
}
else
{
return 0;
}
}
public class LinkedList<T>
{
private int count;
private Node<T> head;
private class Node<T>
{
public T value;
public Node<T> next;
public Node(T data)
{
this.value = data;
this.next = null;
}
}
LinkedList()
{
count = 0;
head = null;
}
void sortedInsert(T data)
{
Node<T> current;
Node<T> new_node = new Node<T>(data);
/* Special case for head node
head.value >= newNode*/
if (head == null || (head.value.compareTo(new_node.value) == 1 || head.value.compareTo(new_node.value) == 0))
{
new_node.next = head;
head = new_node;
}
else {
current = head;
while (current.next != null && (current.next.value.compareTo(new_node.value) == -1))
current = current.next;
new_node.next = current.next;
current.next = new_node;
}
}
You could try to switch to this:
public class LinkedList<T extends Comparable<T>>
The head.value variable is not necessarily something that implements Comparable interface. You need to either define your LinkedList<T> such that it must implement Comparable (see #algrid's answer) or cast it when using the compareTo method.

How to sort a linked list in alphabetical order using Java?

I am doing an library inventory system, so I was supposed to sort the name inside the Node into alphabetical order. I have bookname, author, isbn number, number of copies and genre, all these information I store inside a class.
I do wrote the code for it to sort alphabetically, but it didn't work.
Could someone tell me what's wrong in my code?
Here is my Linked List class contain insert and display method:
public class LinkedList
{
Node node = new Node();
static Node head;
public LinkedList()
{
head=null;
}
public Node getHead()
{
return head;
}
public static void addNode(Data data)
{
Node newNode = new Node(data, head);
if (head == null) {
head = newNode;
newNode.setNext(null);
} else {
Node next = head;
Node prev = next;
do {
if (data.name.compareTo(next.data.name) < 0) {
break;
}
prev = next;
next = next.getNext();
} while (next != null);
newNode.setNext(next);
if (data.name.compareTo(next.data.name) < 0) {
head = newNode;
} else prev.setNext(newNode);
}
}
public static String displayNode()
{
Node current = head;
String output = "";
while(current != null){
output+=current.data.toString();
current = current.next;
}
return output;
}
Here is my Node class:
public class Node
{
Data data;
Node next;
public Node()
{
next = null;
}
Node(Data data, Node next)
{
this.data = data;
this.next = next;
}
public Object getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next=next;
}
}
Here is my Data class:
public class Data {
LinkedList list;
String name;
String author;
int isbn;
int number;
String genre;
public Data(String name, String author, int isbn, int number, String genre)
{
this.name = name;
this.author = author;
this.isbn = isbn;
this.number = number;
this.genre = genre;
}
public String toString()
{
return("Book Name: "+name+"\nAuthor: "+author+"\nISBN Number: "+isbn+"\nNumber of Copies: "+number+"\nGenre: "+genre+"\n\n");
}
public String getName()
{
return name;
}
Here is my Iterator class which I used to display the list:
public class DisplayIterator
{
LinkedList list;
static Node current;
static Node newNode;
DisplayIterator(Node newNode)
{
this.newNode = newNode;
current = list.head;
}
public static boolean hasNext()
{
if(current == null){
return false;
}
else if (current.next == null){
return false;
}
return true;
}
public static Node next()
{
if(hasNext()){
current = current.next;
}
return current;
}
public static void remove(){
throw new UnsupportedOperationException("It is read-only.");
}
}
Thank you.
The following code implements an order based insertion into a linked list. This of course assumes that the list is already sorted. It is safe to make this assumption because the only way in your interface to add nodes to a linked list is via this method.
public static void addNode(Data data) {
Node newNode = new Node(data, head);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null && data.name.compareTo(current.data.name) >= 0) {
current = current.next;
}
if (current == head && data.name.compareTo(current.data.name) < 0) {
newNode.next = head;
head = newNode;
}
else {
newNode.next = current.next;
current.next = newNode;
}
JOptionPane.showMessageDialog(null,"Book Information has been added to the inventory.");
}
I assume, your Node is not the one from java util LinkedList, right? Can you provide the implementation of it? Why does its constructor the head ?
You insert your new element at the begin and try to traverse forward. And at the end of your loop in your current is the first greater and previous the last smaller. Until now correct.
But afterwards, you never use the Previous, and sets the new element to your. You nead to insert it between previous and current. Something like that:
if (previous == null)
head = newData;
else
previous.next = newData;
newData.next = current;
Java has a rich library for sorting for any collection of data
java.util.Collections.sort(YOURLIST_valiable)

What's wrong with this Java Linked List representation of a stack of integers?

Okay, so with the following code I get a nullpointer exception from everything in my pop method. Therefore, I know that 'head' must be null when that method runs. Thing is I have no idea why and I've looked over my code a good bit now. Please help!
Here it is:
NODE CLASS:
public class StackNode{
private StackNode link; //link to next node
private int value;
public StackNode(int value, StackNode linkValue){
this.link = link;
this.value = value;
}
public StackNode(){
this.link = null;
}
public void setNodeData(int value){
this.value = value;
}
public void setLink(StackNode newLink){
this.link = newLink;
}
public int getValue(){
return this.value;
}
public StackNode getLink(){
return link;
}
}
LINKED LIST CLASS:
public class IntStackList{
private StackNode head;
public IntStackList(){ this.head = null; }
public void push(int value){
this.head = new StackNode(value, head);
}
public int pop(){
int value = this.head.getValue(); //get the int value stored in the head node
this.head = head.getLink(); //sets the head to the next node in line
return value;
}
}
I am implementing this in a program that converts a decimal number to binary(for a class). I can print data from the first node AKA the head of the linked list but then I have the null issue when popping again.
You're assigning link to itself in the constructor if the StackNode...
public class StackNode {
private StackNode link; //link to next node
private int value;
public StackNode(int value, StackNode linkValue) {
this.link = link;
this.value = value;
}
It should be
this.link = linkValue;

Deep copying (Linked List)

This is just a test program (my original program gets data from a file so i omitted that since it might complicate people from understanding my problem)
Anyways, I tried deep copying my object data but I'm get a "null" when i print the copy method? what's wrong with the code? is this how we deep copy using recursion? if not, any tips to deep copying? Any other ways to keep copy apart from recursion? I'm not entirely sure if what I'm doing is right honestly since i'm reusing the copy method from a source.
Main
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
Person personTwo = new Person();
personTwo.setFirstName("Steve");
personTwo.setLastName("rivera");
personTwo.setAge(22);
LinkedList lList = new LinkedList();
// add elements to LinkedList
lList.add(person);
lList.add(personTwo);
//node
Node str;
"Variable str might not have been initialized"
//deep copy
Node copy = Node.copy(str);
System.out.println(copy);
}
LinkedList
class LinkedList {
// reference to the head node.
private Node head;
private int listCount;
// LinkedList constructor
public LinkedList() {
// this is an empty list, so the reference to the head node
// is set to a new node with no data
head = new Node(null);
listCount = 0;
}
public void add(Object data) // appends the specified element to the end of this list.
{
Node Temp = new Node(data);
Node Current = head;
// starting at the head node, crawl to the end of the list
while (Current.getNext() != null) {
Current = Current.getNext();
}
// the last node's "next" reference set to our new node
Current.setNext(Temp);
listCount++;// increment the number of elements variable
}
public int size() // returns the number of elements in this list.
{
return listCount;
}
public String toString() {
Node Current = head.getNext();
String output = "";
while (Current != null) {
output += "[" + Current.getData().toString() + "]";
Current = Current.getNext();
}
return output;
}
}
Node
class Node {
// reference to the next node in the chain,
// or null if there isn't one.
Node next;
// data carried by this node.
// could be of any type you need.
Object data;
// Node constructor
public Node(Object dataValue) {
next = null;
data = dataValue;
}
// another Node constructor if we want to
// specify the node to point to.
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
// these methods should be self-explanatory
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
Here is the copy method within the Node class
public static Node copy(Node str) {
if (str == null) {
return null;
}
Node copyFirst = new Node(str.data, null);
copyFirst.next = copy(str.next);
return copyFirst;
}
}
Person
class Person {
private String firstName;
private String lastName;
private int age;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(firstName);
buffer.append(" ");
buffer.append(lastName);
buffer.append(" ");
buffer.append(age);
buffer.append(" ");
return buffer.toString();
}
Thanks
//dummy variable
Node str = null;
//deep copy
Node copy = Node.copy(str);
System.out.println(copy);
What did you expect?
You need to copy the list, not some dummy node. For that, LinkedList needs to support copying (or at least a way to iterate over its elements). Node should be an implementation detail completely hidden from the users of LinkedList.
A shallow copy is when you reuse the node values as is. eg. you loop through your Nodes making new Node with the same values and chaining the new nodes together. You'll need to keep the first as the reference for the new LinkedList object.
A deep copy is when the data is also cloned. If all your objects implements Cloneable you just implement clone as describes above and instead of making new node with the same value you just make a clone of the value for the new Node and voilĂ , you got a deep copy.

Remove in Linked structure

Hello There I am trying to test removeCity(), but it didn't remove any element that I provide.
also the method addToList() if I use it in the City class I get "Exception in thread "main" java.lang.StackOverflowError" while it work fine in the test class
Any help ?
MyList
public class MyList<T> {
private Node head;
private Node tail;
public MyList(){
head = null;
tail = null;
}
public void addToTail(T info){
Node n;
//case 1: empty List
if(isEmpty()){
n = new Node(info, null);
head = n;
tail = head;
}
//case 2: if the list is not empty
else {
n = new Node(info, null);
tail.setNext(n);
tail = n;
}
}
public void addToHead(T info){
Node n;
//case 1: empty List
if(isEmpty()){
n = new Node(info, null);
head = n;
tail = head;
}
//case 2: if the list is not empty
else {
n = new Node(info, head);
head = n;
}
}
public boolean removeHead(){
//Case 1: if the list is empty
if(isEmpty())
return false;
//case 2: if the list have at least one element
else{
Node n = head.getNext();
head = n;
return true;
}
}
public boolean removeElement(String element){
//cacs 1 if before is the head
if(isEmpty())
return false;
if( ((City) head.getInfo()).getCode().equals(element)){
removeHead();
return true;
}
Node iter = head.getNext();
Node prev = head;
while(iter != null && !((City) head.getInfo()).getCode().equals(element)){
iter = iter.getNext();
prev = prev.getNext();
}
if(iter == null)
return false;
else{
prev.setNext(iter.getNext());
return true;
}
}
//To check if the list is empty
public boolean isEmpty(){
if ( head == null)
return true;
else
return false;
}
Node
public class Node<T> {
private T info;
private Node next;
public Node(){
info = null;
next = null;
}
public Node(T info, Node next){
this.info = info;
this.next = next;
}
public T getInfo(){
return info;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
public void setInfo(T info){
this.info = info;
}
}
City
public class City implements Serializable {
public static MyList<City> cityList = new MyList<City>();
private String name;
private String code;
public City(String name, String code) {
super();
this.name = name;
this.code = code;
addToList(new City(name,code));
}
public void addToList(City toAdd){
City.cityList.addToHead(toAdd);
}
public static void removeCity(String name){
if( cityList.isEmpty()){
System.out.println("The List is empty");
return;
}
if ( cityList.removeElement(name) == true )
System.out.println("The City was removed sucssesfully");
else
System.out.println("This city does not not exist");
}
}
Test
public class DummyTest {
public static void main(String [] args){
City x = new City("Ney York","NY");
City y = new City("London","LD");
System.out.println(City.cityList);
}
}
Stacktrace
Exception in thread "main" java.lang.StackOverflowError
at City.<init>(City.java:15)
at City.<init>(City.java:18)
at City.<init>(City.java:18)
Line 15 is the constructor
public City(String name, String code)
Line 18 is addToList
addToList(new City(name,code))
What I've spotted that you have an issue in your while loop in removeElement method.
I am not sure if it will solve your issue.
Could you also put a part of stacktrace here were do you get StackOverflowException.
Node iter = head.getNext();
Node prev = head;
while(iter != null && !((City) head.getInfo()).getCode().equals(element)){
iter = iter.getNext();
prev = prev.getNext();
}
this line
while(iter != null && !((City) head.getInfo()).getCode().equals(element))
should be probably
while(iter != null && !((City) iter.getInfo()).getCode().equals(element))
iter instead head
Alexey already found the first error, here are 2 more:
public City(String name, String code) {
super();
this.name = name;
this.code = code;
addToList(new City(name,code)); // <- infinite recursion
}
is infinite recursion: the (constructor-)method calls the (constructor-)method.
It should probably be addToList(this);
Also: In mylist.java all the new Node(..) should be new Node<T>(..).

Categories