How to display a string in linked list using nodes - java

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;

Related

Passing elements from an array to a linked list

I was trying to make an algorithm that takes some elements into a Linked List and after it passes those elements into an array using Bubble Sort to sort the elements. I sorted those elements but now I'm not able to pass the elements from the array to the Linked List again.
I used the method passIntoArray(Node head, int arr[]) to take the elements from the Linked List and pass into the array. The method count(Node head) is used to check how many elements there were in the Linked List(Currently being used as index of the array). Could anyone help me?
package LinkedList;
public class LinkedListSorting {
private static int count(Node head) {
if (head == null) return 0;
Node current = head;
int count = 0;
while(current != null) {
count++;
current = current.next;
} return count;
}
private static void passIntoArray(Node head, int arr[]) {
if (head == null) return;
Node current = head;
int i = 0;
while(current != null) {
arr[i] = current.data;
i++;
current = current.next;
}
int length = count(head);
for(i=0; i<length; i++) {
for(int j=i+1; j<length; j++) {
if(arr[i]>arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<length; i++) {
System.out.println(arr[i]);
}
}
//FROM THE ARRAY TO THE LL
private static void display(Node head) {
if (head == null) return;
Node current = head;
while(current != null) {
System.out.print(current.data + " --> ");
current = current.next;
} System.out.println(current);
}
private static class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public static void main(String args[]) {
Node head = new Node(5);
Node first = new Node(2);
Node second = new Node(3);
Node third = new Node(4);
Node fourth = new Node(1);
head.next = first;
first.next = second;
second.next = third;
third.next = fourth;
display(head);
System.out.println();
int arr[] = new int[count(head)];
passIntoArray(head, arr);
System.out.println();
}
}
I guess you want to sort the elements of the linked list
It would be better if you sort them in the linked list itself.
public class Main {
private static int count(Node head) {
if (head == null) return 0;
Node current = head;
int count = 0;
while(current != null) {
count++;
current = current.next;
} return count;
}
private static void sortLL(Node head) {
if (head == null) return;
Node current = head;
Node i,j;
int length = count(head);
for(i=head; i!=null; i=i.next) {
for(j=i.next; j!=null; j=j.next) {
if(i.data>j.data) {
int temp = i.data;
i.data = j.data;
j.data = temp;
}
}
}
}
private static void display(Node head) {
if (head == null) return;
Node current = head;
while(current != null) {
System.out.print(current.data + " --> ");
current = current.next;
} System.out.println(current);
}
private static class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public static void main(String args[]) {
Node head = new Node(5);
Node first = new Node(2);
Node second = new Node(3);
Node third = new Node(4);
Node fourth = new Node(1);
head.next = first;
first.next = second;
second.next = third;
third.next = fourth;
sortLL(head);
display(head);
}
}

Adding to the tail of a linked list

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;

Adding Node to Initially Null LinkedList

I'm having issues when I try to add a node to a linked list that is initialized to null. In my method I set a test case to check if the node is initially null and if so it creates a new node with the value that was passed in. But for whatever reason it doesn't work unless the node has atleast one element already passed in. Check it out:
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
//Driver Class
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
The above code will not run if myNode is initialized to a null value (Node myNode = null;)
Full Code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static class Node
{
private int value;
Node next;
public Node()
{
next = null;
}
public Node(int val)
{
value = val;
next = null;
}
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
Node current = null;
Node oddFirst = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
current = myNode;
while(current != null) // Check if values were copied correctly
{
if(oddFirst == null)
{
oddFirst = new Node(current.value);
}
oddFirst.addNode(oddFirst,current.value);
//oddFirst = current.next;
//oddFirst = oddFirst.next;
current = current.next.next;
}
while(oddFirst != null)
{
System.out.println("Current Value: " + oddFirst.value);
oddFirst = oddFirst.next;
}
}
}
A simple solution for a linked list:
class Node {
int val;
Node next;
}
public class LinkedList {
public Node first;
public Node last;
public void addNext(int val) {
Node node = new Node();
node.val = val;
if(last == null) {
first = last = node;
}
else {
last.next = node;
last = node;
}
}
}
The main issue with the original code is that it doesn't concern itself with the case of the empty list.
You cannot discern the case where the list is comprised of a single 1 value, and the empty list.
Because you're not handling the return value of addNode().
You're returning a Node in the following function:
Node addNode(Node node, int val)
but you're not handling the return here:
myNode.addNode(myNode, inputVal);
This should help you figure out the solution.

Infinite loop is occurring. How to fix it?

import java.util.Scanner;
public class reverse {
private Node head;
private int listCount;
public reverse() {
head = new Node(null);
listCount = 0;
}
public static void main(String args[]) {
reverse obj = new reverse();
Scanner sc = new Scanner(System.in);
int n, i, x;
System.out.println("How many no.s?");
n = sc.nextInt();
for (i = 1; i <= n; i++) {
System.out.println("enter the no.");
x = sc.nextInt();
obj.add(x);
}
Node newhead = obj.method1(obj.head);
obj.display(newhead);
}
public void add(Object data) {
Node temp = new Node(data);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
listCount++;
}
public void display(Node newhead) {
Node current = newhead;
//System.out.println(current.getNext().getNext().getNext().getNext().getNext().getData());
while (current != null) {
System.out.print(current.getData() + " " +);
current = current.getNext();
}
}
public Node method1(Node head) {
if (head == null) {
return head;
}
Node first = head.getNext();
Node second = first.getNext();
first.setNext(head);
head = null;
if (second == null)
return head;
Node current = second;
Node prev = first;
while (current != null) {
Node upcoming = current.getNext();
current.setNext(prev);
prev = current;
current = upcoming;
//System.out.println(prev.getData());
//System.out.println(current.getData());
}
head = prev;
return head;
}
private class Node {
Node next;
Object data;
public Node(Object _data) {
next = null;
data = _data;
}
public Node(Object _data, Node _next) {
next = _next;
data = _data;
}
public Object getData() {
return data;
}
public void setData(Object _data) {
data = _data;
}
public Node getNext() {
return next;
}
public void setNext(Node _next) {
next = _next;
}
}
}
My while statement is not working properly.
Initial value of newhead.getData() is 5. The comment part in my code is also giving value as null which is correct, but after that there is some error in my while loop.
I have written code for reversing a linked list.
display() method is to print all the list elements.
Input from user of linked list is:
1 2 3 4 5
Output should be:
5 4 3 2 1
But my output is:
null 1 null 1 null 1............occurring infinite times.
you have a problem when you a filling your data .
all nods have the same reference
try to print your list
for(int i=;i;list.size();i++)
System.out.print(list.getObjectAtIndex(i).getData);

Deleting a node from a list

My problem: My delete node method works fine for deleting any specified node from a user created list except for the first element. How do I get this method to be able to delete the front of a list?
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
}
This is the full program code.
import java.io.*;
public class LinkedList {
public int num;
public node front;
//set front to null
public void init() {
front = null;
}
//make a new node
public node makeNode(int num) {
node newNode = new node();
newNode.data = num;
newNode.next = null;
return newNode;
}
//find the end of a list
public node findTail(node front) {
node current = front;
while(current.next != null) {
current = current.next;
}
return current;
}
//find a specified node
public node findSpot(node front, int num) {
node current = front;
boolean searching = true, found = false;
while((searching)&&(!found)) {
if(current == null) {
searching = false;
}
else if(current.data == num) {
found = true;
}
else {
current = current.next;
}
}
return current;
}
//delete a specified node
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
}
//add nodes to the end of a list
public void add2Back(node front, int num) {
node tail;
if (front == null) {
front = makeNode(num);
}
else {
tail = findTail(front);
tail.next = makeNode(num);
}
}
//add nodes after a specified node
public void addAfter(int num, node spot) {
node newNode;
newNode = makeNode(num);
newNode.next = spot.next;
spot.next = newNode;
}
//print out a list
public void showList(node front) {
node current = front;
while(current != null){
System.out.println(current.data);
current = current.next;
}
}
public static void main(String [] args) throws IOException{
//make a new list and node
LinkedList newList = new LinkedList();
node newNode = new node();
//add data to the nodes in the list
for(int j = 1; j < 10; j++){
newList.add2Back(newNode, j);
}
//print out the list of nodes
System.out.println("Auto-generated node list");
newList.showList(newNode);
//ask the user how many nodes to make, make those nodes, and show them
System.out.println("Please enter how many nodes you would like made.");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData = inputReader.readLine();
int listLength = Integer.parseInt(inputData);
LinkedList userList = new LinkedList();
node userNode = new node();
for(int j = 1; j < listLength; j++) {
userList.add2Back(userNode, j);
}
userList.showList(userNode);
//ask the user to add a new node to the list after a specified node
System.out.println("Please enter a number for a node and then choose a spot from the list to add after.");
BufferedReader inputReader2 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData2 = inputReader2.readLine();
BufferedReader inputReader3 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData3 = inputReader3.readLine();
int newNodeValue = Integer.parseInt(inputData2);
int nodeInList = Integer.parseInt(inputData3);
userList.addAfter(newNodeValue, userList.findSpot(userNode, nodeInList));
userList.showList(userNode);
//ask the user to delete a specified node
System.out.println("Please enter a node to delete.");
BufferedReader inputReader4 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData4 = inputReader4.readLine();
int nodeToDelete = Integer.parseInt(inputData4);
userList.deleteNode(userList.findSpot(userNode, nodeToDelete), userNode);
userList.showList(userNode);
}
}
The problem is that your deleteNode does not modify the front member variable of your list, because the front variable inside deleteNode is a method parameter, not the instance variable front.
Here is what you need to do:
Exposing front as a public member of the LinkedList is a violation of encapsulation. Make front a private variable.
Remove parameter front from all methods that take it; use the private member front instead.
Add a check in deleteNode to see if the spot to be deleted is the front. If it is, perform a special operation that assigns front a new value, and exit; otherwise, do the while loop that you already have.
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
if(front == spot) {
front = null;
return;
}
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
current = null;
}
you are starting to check from the front.next. So front itself is being ignored each time.
Delete a node from linklist in PHP by just passing that value to
linklist delete method....
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//deleting a node from linklist $key is the value you want to delete
public function deleteNode($key)
{
$current = $this->firstNode;
$previous = $this->firstNode;
while($current->data != $key)
{
if($current->next == NULL)
return NULL;
else
{
$previous = $current;
$current = $current->next;
}
}
if($current == $this->firstNode)
{
if($this->count == 1)
{
$this->lastNode = $this->firstNode;
}
$this->firstNode = $this->firstNode->next;
}
else
{
if($this->lastNode == $current)
{
$this->lastNode = $previous;
}
$previous->next = $current->next;
}
$this->count--;
}
}
$obj = new LinkList();
$obj->deleteNode($value);
}
?>
linklist delete method....
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
}

Categories