Adding Node to Initially Null LinkedList - java

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.

Related

JAVA- Printing out LinkedLists in an ArrayList [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 1 year ago.
I am trying to print out the elements in my ArrayList that looks like
static ArrayList<LinkedList> listy = new ArrayList<>();
I tried to create a function called PrintTest()
public static void pTest() {
String [] top;
for (LinkedList i: listy) {
//i.show();
System.out.println(i.toString());
However, I am still getting when I call printTest()
LinkedList#15975490
LinkedList#6b143ee9
LinkedList#1936f0f5
LinkedList#6615435c
LinkedList#4909b8da
LinkedList#3a03464
LinkedList#2d3fcdbd
LinkedList#617c74e5
Do I need to iterator over this once more? I am confused on how to go about this. Can I override toString()? I can't seem to get it to work
Here is my linkedlist implementation code
public class LinkedList {
Node head;
Node tail;
public String getFirst() {
Node node = head;
if (node.next == null) {
throw new NoSuchElementException();
}
else {
return node.data;
}
}
public void insert(String data) {
Node node = new Node();
node.data = data;
node.next = null;
if (head == null) {
head = node;
}
else {
Node n = head;
while(n.next !=null) {
n = n.next;
}
n.next = node;
}
}
public void insertAtStart(String data) {
Node node = new Node();
node.data = data;
node.next = null;
node.next = head;
head = node;
}
public void insertAt(int index, String data) {
Node node = new Node();
node.data = data;
node.next = null;
if(index == 0) {
insertAtStart(data);
}
else {
Node n = head;
for (int i = 0; i < index-1; i++) {
n = n.next;
}
node.next = n.next;
n.next = node;
}
}
public void deleteAt(int index) {
if (index == 0) {
head = head.next;
}
else {
Node n = head;
Node n1 = null;
for (int i = 0; i < index-1; i++) {
n = n.next;
}
n1 = n.next;
n.next = n1.next;
//System.out.println("n1 " + n1.data);
n1 = null;
}
}
public int size() {
int count =0;
Node pos = head;
while (pos != null) {
count++;
pos = pos.next;
}
return count;
}
public void remove(String s) {
Node node = head;
while (!node.data.equals(s)) {
node = node.next;
}
if (node.next == null) {
node.data = null;
}
else {
node.data = node.next.data;
node.next = node.next.next;
}
//System.out.println("n1 " + n1.data);
}
public void show() {
Node node = head;
while(node.next != null) {
System.out.println(node.data);
node = node.next;
}
System.out.println(node.data);
In java, every class inherits the Object class. In the Object class default definition for the toString method is hashcode. When you are calling toString method, you need to define by yourself.
class LinkedList{
int value;
#Override
public String toString(){
return String.valueOf(value);
}
}
I think you can go through this article to get more understanding.Explanation For toString

getting no desired output on printing down the LinkedList in revers form

I wrote down the code to print the list in reverse form and after I found that I am not getting desired output, as per my thinking It should work, but it doesn't. after checking a lot of time I tried to find the problem but still getting no output.
Don't compare the code with the complexity because I know the complexity is not well. This is just an idea to bring up the all possible outcomes.
Here is the code:
import java.util.*;
public class printReverse {
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
static class SinglyLinkedList {
public Node head;
public Node tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
}
// Insert the node to the LinkedList method
static void add (Node head, int data) {
Node node = new Node(data);
Node current = head;
if (head == null) {
head = node;
}
else {
current.next = node;
}
current = node;
}
// ArrayList insertion
static void insert (Node head, ArrayList<Integer> a) {
Node current = head;
while (current != null) {
a.add(current.data);
current = current.next;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
SinglyLinkedList list = new SinglyLinkedList();
int n = scan.nextInt();
for (int j = 0; j < n; j++) {
int value = scan.nextInt();
add(list.head, value);
}
ArrayList<Integer> array = new ArrayList<>();
insert(list.head, array);
// Printing ArrayList revsrse
System.out.println(array);
}
scan.close();
}
}
The problem is not adding the node value to the linked list to the (add) method.
code needed a few changes.
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
public Node head;
public Node tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
// Insert the node to the LinkedList method
public void add (Node node) {
if (node != null) {
head.next = node;
head = node;
}
if (tail == null) {
tail = node;
}
}
public void print (Node node) {
if (node.next != null) {
print(node.next);
}
System.out.println(node.data);
}
}
in the main method you can call add method alone if you want to add any node to the list.
SinglyLinkedList list = new SinglyLinkedList();
this code should be out side of the loops because you want a single linked list, if you want to have multiple single linked lists then you can have them inside a loop.
to print the list elements you can traverse all the nodes from tail and print the data with in it. you cannot traverse back from head as head doesn't contain previous node reference.

Linked List only displaying the first node

import java.io.*;
import java.util.*;
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class practice {
public static Node insert(Node head, int d) {
if (head == null)
head = new Node(d);
else {
Node cn = head;
while (cn != null) {
cn = cn.next;
cn = new Node(d);
cn = cn.next;
}
}
return head;
}
public static void display(Node head) {
Node start = head;
while (start != null) {
System.out.print(start.data + " ");
start = start.next;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Node head = null;
int N = sc.nextInt();
while (N-- > 0) {
int ele = sc.nextInt();
head = insert(head, ele);
}
display(head);
}
}
I was trying to create a linked list with head as the node pointing the starting node of the list. And adding n elements to the tail of the list. But when trying to display the list, I am getting only the first element as the output.
For example,
for the input
3
4
5
6
The output is 4 when it should be 4 5 6
Your insert method fails to insert any node in the case that the head already exists. It creates a new Node, but then ignores it.
Instead, search for the end of the list, looking for a null next reference. Then, set the next reference to a new Node.
else
{
Node cn = head;
while (cn.next != null)
{
cn = cn.next;
}
cn.next = new Node(d);
}

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