I have an append method for my linked list where I want to add to the tail, however when a new node is added to the list, headNode and tailNode both become the newly inserted node. How do I keep headNode to stay as the first node that was entered into the list and not have it become the same thing as tailNode.
public static void append()
{
for(int x = 0; x < gradeArray.length; x++)
{
if(gradeArray[x] < 70)
{
StudentNode newNode = new StudentNode(nameArray[x], gradeArray[x], null);
if(headNode == null)
{
headNode = newNode;
}
else
{
tailNode.nextNode = newNode;
}
tailNode = newNode;
}
}
}
I am not sure what mistake are you doing but see below this code is working perfectly fine.
public class Grades {
public static String[] nameArray = new String[50];
public static int[] gradeArray = new int[50];
public static StudentNode headNode;
public static StudentNode tailNode;
public static void append() {
for (int x = 0; x < gradeArray.length; x++) {
if (gradeArray[x] < 70) {
String name = nameArray[x];
int grade = gradeArray[x];
StudentNode newNode = new StudentNode(name, grade, null);
if (headNode == null) {
headNode = newNode;
} else {
tailNode.nextNode = newNode;
}
tailNode = newNode;
}
}
}
public static void main(String[] args) throws java.lang.Exception {
for (int i = 0; i < 50; i++) {
nameArray[i] = "name-" + i;
gradeArray[i] = i;
}
append();
for(int i=0; i<50; i++) {
nameArray[i] = "name-" + (i + 50);
gradeArray[i] = i + 50;
}
append();
System.out.println(headNode.toString());
System.out.println(tailNode.toString());
}
}
class StudentNode {
public int grade;
public String name;
public StudentNode nextNode;
public StudentNode(String n, int g, StudentNode sn) {
name = n;
grade = g;
nextNode = sn;
}
public String toString() {
return name + ", " + grade;
}
}
Even if you change grade and name arrays and run append again it still keeps the head correct.
Ideone link for running code
Why did you append this statement ? tailNode = newNode;
Imagine, thread goes through by if(headNode == null) he assign newNode adress to headNode . After that, tailNode = newNode; is executed and tail pointing to newNode.
Finally, tailNode and headNode point to the same object : newNode.
I think you have to delete this statement tailNode = newNode;
Related
I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.
Use an inner class for the Node.
Include the methods below.
Write a tester to enable you to test all of the methods with whatever data you want in any order.
I have to create a method called "public void addToBack(int item)". This method is meant to "Add an Item to the end of the list" I have my code for this method down below. When I execute this method my list becomes empty. Does someone know what I did wrong and how to fix it?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public void addToBack(int x) {
if (head == null) {
head = new Node(x, head);
return;
}
tail = head;
while (tail.nextNode != null) {
tail = tail.nextNode;
}
tail.nextNode = new Node(x, tail);
}
public String toString() {
String result = "";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
if (!result.isEmpty()) {
result += ", ";
}
result += ptr.value;
}
return "[" + result + "]";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
boolean done = false;
while (!done) {
System.out.println("1. Add to Back");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Add an Item to the Back of a List.");
list.addToBack(input.nextInt());
break;
case 2:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
When you add to the tail the nextNode should point to null
tail.nextNode = new Node(x, null);
At the moment you are having an endless loop
Hey I can't seem to get my code to work, there is something wrong with the constructor and I just can't figure out what it is.
I had it working for the constructor and tried it for some of the methods but even then it still gave me NullPointerException
import java.util.NoSuchElementException;
public class LinkedString
{
//Required Nodes/counters to track positions in LinkedList
private Node start;
private Node end;
private int counter;
private int i = 0;
//Inner class Node provides the node object required to create links
private class Node
{
public char data;
public Node next;
}
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
//This accessor returns a value at the specified index
//The 1st character has an index of 0 and will throw
//a no such element exception if there is no char # given index
public char charAt(int index)
{
Node current = start;
boolean found = false;
char temp = 0;
int i = 0;
while (current.next != null && i <= index)
{
current = current.next;
if(i == index)
{
found = true;
//Return done, and Data is wrong Edit.
}
i++;
temp = current.data;
}
if(found == false) {
throw new NoSuchElementException();
}
return temp;
}
//concat connects two linkedString objects together and updates the
//counter for how many chars are in the combined list
public LinkedString concat(LinkedString value)
{
end.next = value.start;
end = value.end;
counter = counter + value.length();
return value;
}
//isEmpty checks to see if the list has a initial value
//if it doesnt its empty and returns true
public boolean isEmpty()
{
if(start == null)
{
return true;
}
else
{
return false;
}
}
//length() returns the counter variable which counts the number of
// characters in the linked string
public int length()
{
return counter;
}
//substring returns a copy of the linked string from a specified point
//to another, if the user attempts to copy a value from a not existing
//index point it throws NoSuchElementException
public Node substring(int startIndex, int endIndex)
{
Node current = start;
Node sIndex;
Node eIndex;
Node copy = null;
int i = 0;
while(current.next != null && i <= startIndex)
{
current = current.next;
if(i == startIndex)
{
sIndex = current;
sIndex.next = copy;
while(current.next != null && i <= endIndex)
{
current = current.next;
copy.next = current;
copy = current;
if(i == endIndex)
{
eIndex = current;
eIndex.next = null;
copy.next = eIndex;
}
i++;
}
if(i < endIndex)
throw new NoSuchElementException();
}
i++;
}
return copy;
}
}
public class LinkedStringMain {
public static void main(String[] args) {
LinkedString linked = new LinkedString("stack");
System.out.println(" " + linked.charAt(0));
System.out.println(" " + linked.isEmpty());
}
}
The error is that start is not being initialized in your either of your constructors after you check if it is null. To fix this, initialize start using start = new Node();. The changes are implemented below:
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start = new Node(); //initialize start
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start = new Node(); //initialize start
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
My code is as follows:
import net.datastructures.Node;
public class SLinkedListExtended<E> extends SLinkedList<E> {
public int count(E elem) {
Node <E> currentNode = new Node <E>();
currentNode = head;
int counter = 0;
for (int i = 0; i<size; i++){
if (currentNode == null) {
return 0; //current is null
}
else if (elem.equals(currentNode.getElement())){
counter++;
currentNode = currentNode.getNext();
}
}
return counter;
}
public static void main(String[] args) {
SLinkedListExtended<String> x = new SLinkedListExtended<String>();
x.insertAtTail("abc");
x.insertAtTail("def");
x.insertAtTail("def");
x.insertAtTail("xyz");
System.out.println(x.count("def")); // should print "2"
//x.insertAtTail(null);
x.insertAtTail("def");
//x.insertAtTail(null);
System.out.println(x.count("def")); // should print "3"
//System.out.println(x.count(null)); // should print "2"
}
}
The method count is supposed to return the number of the amount of times a given element, elem is found in a list. I have written this loop but only get a return of 0 every time. A nullpointerexception is also thrown.
Edit: SLinkedList SuperClass
import net.datastructures.Node;
public class SLinkedList<E> {
protected Node<E> head; // head node of the list
protected Node<E> tail; // tail node of the list (if needed)
protected long size; // number of nodes in the list (if needed)
// default constructor that creates an empty list
public SLinkedList() {
head = null;
tail = null;
size = 0;
}
// update and search methods
public void insertAtHead(E element) {
head = new Node<E>(element, head);
size++;
if (size == 1) {
tail = head;
}
}
public void insertAtTail(E element) {
Node<E> newNode = new Node<E>(element, null);
if (head != null) {
tail.setNext(newNode);
} else {
head = newNode;
}
tail = newNode;
size++;
}
public static void main(String[] args) { // test
}
}
It seems you missed to go to the next node if non of both condition match.
public int count(E elem) {
Node <E> currentNode = new Node <E>();
currentNode = head;
int counter = 0;
for (int i = 0; i<size; i++){
if (currentNode == null) {
return 0; //current is null
}
else if (elem.equals(currentNode.getElement())){
counter++;
}
currentNode = currentNode.getNext();
}
return counter;
}
MrSmith's answer nails it, I think. I would not use size for the loop but take the fact that there is no next as bottom. Of course your count method then has to return the counter in all cases and not 0.
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;
I created a linked list using nodes that prints out a list(string) of names. I'm trying to write a sort method that prints out the names in alphabetical order. If this was integers it would be easy but I have no idea how to go about doing this. Any help or tips are appreciated.
-I cannot use the builtin collections.sort(). I need to make my own method.
SortMethod: (this is what I used when I was printing a list of numbers out but now its strings so I know I can't use the > operator. I just don't know how to replace it.
public void Sort( BigNode front)
{
BigNode first,second,temp;
first= front;
while(first!=null) {
second = first.next;
while(second!=null) {
if(first.dataitems < second.dataitems)
{
temp = new BigNode();
temp.dataitems =first.dataitems;
first.dataitems = second.dataitems;
second.dataitems = temp.dataitems;
}
second=second.next;
}
Heres the rest of program(I dont think its needed but just in case)
import java.util.*;
public class BigNode {
public String dataitems;
public BigNode next;
BigNode front ;
BigNode current;
String a = "1", b = "2", c = "3", d = "4";
String[] listlength;
public void initList(){
front = null;
}
public BigNode makeNode(String number){
BigNode newNode;
newNode = new BigNode();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(BigNode front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public BigNode findTail(BigNode front) {
BigNode 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(BigNode front ,String name){
BigNode tail;
if(isListEmpty(front)){
this.front = makeNode(name);
}
else {
tail = findTail(front);
tail.next = makeNode(name);
}
}
public void addAfter(BigNode n, String dataItem2) { // n might need to be front
BigNode temp, newNode;
temp = n.next;
newNode = makeNode(dataItem2);
n.next = newNode;
newNode.next = temp;
}
public void findNode(BigNode front, String value) {
boolean found , searching;
BigNode curr;
curr = front;
found = false;
searching = true;
while ((!found) && (searching)) {
if (curr == null) {
searching = false;
}
else if (curr.dataitems == value) { // Not sure if dataitems should be there (.data in notes)
found = true;
}
else {
curr = curr.next;
}
}
System.out.println(curr.dataitems);
}
public void deleteNode(BigNode front, String value) {
BigNode curr, previous = null; boolean found;
if (!isListEmpty(front)){
curr = front;
found = false;
while ((curr.next != null) && (!found)) {
if(curr.dataitems.equals(value)) {
found = true;
}
else {
previous = curr;
curr = curr.next;
}
}
if (!found) {
if(curr.dataitems.equals(value)) {
found = true;
}
}
if (found) {
if (curr.dataitems.equals(front.dataitems)){ // front.dataitems may be wrong .dataitems
front = curr.next;
} else {
previous.next = curr.next;
}
} else {
System.out.println("Node not found!");
//curr.next = null; // Not sure If this is needed
}
}
showList(front);
}
public void printNodes(String[] len){
listlength = len;
int j;
for (j = 0; j < len.length; j++){
addNode(front, len[j]);
} showList(front);
}
public void showList(BigNode front){
current = front;
while ( current.next != null){
System.out.print(current.dataitems + ", ");
current = current.next;
}
System.out.println(current.dataitems);
MenuOptions();
}
public void MenuOptions() {
Scanner in = new Scanner(System.in);
System.out.println("Choose an Option Below:");
System.out.println(a + "(Display Length of List)" + ", " + b + "(Delete a person)" + ", " + c + ("(Exit)"));
String pick = in.nextLine();
if (pick.equals(b)) {
System.out.println("Who would you like to delete?");
String delete = in.nextLine();
deleteNode(front, delete);
}
if (pick.equals(a)) {
System.out.println("Length of List = " + listlength.length);
MenuOptions();
}
if (pick.equals(c)) {
}
}
public static void main(String[] args) {
String[] names = {"Billy Joe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
x.printNodes(names);
}
}
first.dataitems.compareTo(second.dataitems)<0
or if you have a comparator
comp.compare(first.dataitems, second.dataitems)<0