Linked List only displaying the first node - java

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);
}

Related

Singly Linked List ask user n size of node and put an element in each node in java [duplicate]

This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 1 year ago.
I can only output it to
12345
54321
how can i ask user to input size of nodes
and put elements depending on the size of node
it should be like this:
Sample Output:
Input the number of nodes : 3
Input data for node 1 : 5
Input data for node 2 : 6
Input data for node 3 : 7
Data entered in the list are : 5 6 7
The list in reverse are : 7 6 5
public class LinkedList
{
private Node head;
private Node current;
private static class Node
{
private int data;
private Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public void display()
{
Node current = head;
while (current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println("null");
}
public void reverse()
{
Node next = head;
Node previous = null;
current = null;
while(next != null)
{
current = next;
next = next.next;
current.next = previous;
previous = current;
head = current;
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
LinkedList list = new LinkedList();
System.out.print("Eneter number of nodes: ");
int size = sc.nextInt();
//this is the part where I need a user input
//for node size and put elements in each nodes
list.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
Node fifth = new Node(5);
list.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
list.display();
list.reverse();
list.display();
}
}
You can create an insert method to handle insertion easily
public class LinkedList {
private static class Node {
private final int data;
private Node next;
public Node(int data) {
this.data = data;
}
}
private Node root;
public LinkedList() {
this.root = null;
}
public void insert(int value) {
if (root == null) {
root = new Node(value);
return;
}
Node head = root;
while (head.next != null) head = head.next;
head.next = new Node(value);
}
public void display() {
Node current = root;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public void reverse() {
Node next = root;
Node previous = null;
Node current;
while (next != null) {
current = next;
next = next.next;
current.next = previous;
previous = current;
root = current;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList list = new LinkedList();
System.out.print("Enter number of nodes: ");
int size = sc.nextInt();
for(int i = 0; i < size ; i++) {
System.out.print("Input data for node " + i + ": ");
list.insert(sc.nextInt());
}
list.display();
list.reverse();
list.display();
}
}

How do I fix the following code so I get a reversed linked list for the output?

The following code is my attempt at implementing SinglyLinkedListNode and SinglyLinkedList classes and use the SinglyLinkedListNode reverse(SinglyLinkedListNode head) method to reverse this linked list.
The input consists of the first line detailing the number of test cases, t. And for each test case, the first line, n, represents the number of elements in the linked list. The next n number of lines will each contain an element from this list such that the input is as follows:
1 (number of test cases)
5 (number of elements in list)
1 (element in list)
2 (element in list)
3 (element in list)
4 (element in list)
5 (element in list)
How can I fix the following code so that it can print this reversed linked list, such that the output would be as follows:
5 4 3 2 1
As my code instead prints out the following:
1
5
1
2
3
4
5
1 2 3 4 5
My code:
import java.util.Scanner;
public class ReverseLinkedList {
static class SinglyLinkedListNode {
public int data;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(int nodeData) {
data = nodeData;
next = null;
}
}
static class SinglyLinkedList {
private SinglyLinkedListNode head;
private SinglyLinkedListNode tail;
public SinglyLinkedList() {
SinglyLinkedListNode head = null;
SinglyLinkedListNode tail = null;
}
public void insertNode(int nodeData) {
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
public SinglyLinkedListNode reverse(SinglyLinkedListNode head) {
SinglyLinkedListNode previous = null;
SinglyLinkedListNode current = head;
SinglyLinkedListNode next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public void printLinkedList() {
SinglyLinkedListNode node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SinglyLinkedList list = new SinglyLinkedList();
int testCases = input.nextInt();
if (testCases <= 10) {
input.nextLine();
int size = input.nextInt();
if (size <= 1000) {
for (int i = 0; i < size; i++) {
list.insertNode(input.nextInt());
}
list.reverse(list.tail);
list.printLinkedList();
}
}
}
}
use list.reverse(list.head)
and modify your reverse method as
SinglyLinkedListNode previous = null;
SinglyLinkedListNode current = head;
SinglyLinkedListNode next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head= previous;
return head;
Also in your method printLinkedList set
SinglyLinkedListNode node = tail; // instead of head
You should pass head of the linkedlist instead of tail to reverse method.
list.reverse(list.head);

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);

Practicing Singly Linked List implementation, stumped by my list reversal method throwing NullPointerException

Here is my singly linked list code:
public class SinglyLinkedList {
private static Node head;
private static int listSize;
private static class Node {
int value;
Node next;
Node(int i) {
value = i;
next = null;
}
}
public static void main(String[] args) {
head = null;
listSize = 0;
for (int i = 0; i < 10; i++) {
Node n = new Node(i);
if (head == null) {
head = n;
} else {
getLastNode(head).next = n;
}
listSize++;
}
printNodeValues(head);
Node revHead = reverseList(head);
printNodeValues(revHead);
}
private static Node reverseList(Node head) {
Node reverseHead = getLastNode(head);
Node reference = reverseHead;
while (listSize>0){
Node temp = getPreviousNode(reference, head);
Node last = getLastNode(reverseHead);
temp.next = null;
last.next = temp;
reference = temp;
listSize--;
}
return reverseHead;
}
private static Node getPreviousNode(Node reference, Node head) {
Node temp = head;
while (temp != null) {
if (temp.next == reference) {
break;
} else {
temp = temp.next;
}
}
return temp;
}
private static Node getLastNode(Node n) {
Node temp = n;
while (temp != null) {
if (temp.next == null) {
break;
} else {
temp = temp.next;
}
}
return temp;
}
public static void printNodeValues(Node h) {
while (h != null) {
System.out.print(h.value + " ");
h = h.next;
}
System.out.println();
}
}
The problem is with my reverseList(Node) method. When I run the program, I get the following error:
Exception in thread "main" java.lang.NullPointerException
at SinglyLinkedList.reverseList(SinglyLinkedList.java:44) -> temp = null;
at SinglyLinkedList.main(SinglyLinkedList.java:33) -> Node revHead = reverseList(head);
My printNodeValues works fine, and prints
0 1 2 3 4 5 6 7 8 9
and I'm trying to use reverseList to print
9 8 7 6 5 4 3 2 1 0.
There are many very bad things in your code. Worst of all : why is everything static ? What's the point of writing a list class that can be instantiated only once ?
Then, the size of the list should never be affected by a reverse operation, and you don't even need a counter since you just have to iterate over the list until you find a node which has no successor.
private static Node reverseList(Node head) {
Node res = null;
while (head != null) {
Node node = new Node(head.value);
node.next = res;
res = node;
head = head.next;
}
return res;
}
Your reverseList() method needs to skip the iteration when it has reached the first node in the original list because it's previous node doesn't exist. This first node has already be assigned as the next node (i.e. the last node in the reversed list) in the second last iteration (of your original loop).
private static Node reverseList(Node head) {
Node reverseHead = getLastNode(head);
Node reference = reverseHead;
int counter = listSize;
while ( counter > 1) {
Node temp = getPreviousNode(reference, head);
Node last = getLastNode(reverseHead);
temp.next = null;
last.next = temp;
reference = temp;
counter--;
}
return reverseHead;
}
Secondly, you shouldn't modify your listSize variable directly because the number of elements in the reversed list remains the same. Here, I'm storing it in a temporary counter first before iterating the list.
And, finally the reversed list should become your current head. Since, you've modified the linking between all the elements, it can only be traversed if your head now points to the new head.
printNodeValues(head);
head = reverseList(head);
printNodeValues(head);

Categories