I am adding elements in a Linked List via scanning the elements one by one using a for loop, but at the end there is a 0 coming while printing the list. The last node is pointing to null but still the list is having one element that is 0. I am providing my source code below and then inputs
import java.util.Scanner;
import static java.lang.System.out;
class Node{
int data;
Node next;
Node(){
this.next=null;
}
Node(int data){
this.data=data;
this.next=null;
}
}
public class MyClass{
public static void main(String args[]) {
Node head=new Node();
Node temp=head;
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
for(int i=1;i<=size;i++){
temp.data=sc.nextInt();
temp.next=new Node();
temp=temp.next;
}
temp=null;
while(head!=null){
out.print(head.data+" ");
head=head.next;
}
}
}
Inputs:
5 1 2 3 4 5
The next pointer in the last node of a linked list should be null to denote that it is the last node.
In your case, you are keeping it 'not null'. In your for loop, just don't instantiate the next pointer if it is the last element you are reading.
for(int i=1;i<=size;i++){
temp.data=sc.nextInt();
if(i != size) {
temp.next=new Node();
temp=temp.next;
}
}
The problem is that even though you are setting temp=null after you exit your loop, you still have one extra unassigned node.
The simplest fix is to remove the '=' sign in your for loop so that you exit the loop after your last node and then assign your final value, like this:
for(int i=1;i<size;i++){
temp.data=sc.nextInt();
temp.next=new Node();
temp=temp.next;
}
temp.data=sc.nextInt();
You're creating the head-node outside of the loop and a new node within it.
You therefore get 1 extra node.
You might try the following:
public static void main(String args[]) {
Node head=null;
Node last=null;
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
for(int i=1;i<=size;i++){
if (head == null){
head = new Node();
last = head;
} else {
last.next = new Node();
last = last.next();
}
last.data=sc.nextInt();
}
while(head!=null){
out.print(head.data+" ");
head=head.next;
}
}
Related
I am doing the program for removing nth element from end of the linked list. But problem is that when my size of lined list is equal to n then it is not returning head.next. Where I am doing wrong?
class Main{
static class Node {
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
Node head = null;
public void addFirst(int data) {
Node newnode = new Node(data);
if(head ==null){
head = newnode;
return;
}
newnode.next = head;
head = newnode;
}
//print list
public void PrintLL() {
Node n = head;
if(n.next==null){
System.out.println("NULL");
return;
}
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
}
//Find nth node from last
public Node RemoveNthNode(Node head,int nth){
if(head.next==null){
return null;
}
int size=0;
Node curNode=head;
while(curNode!=null){
curNode = curNode.next;
size++;
}
if(nth==size){
return head.next;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
return head;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
System.out.println("\n");
ll.RemoveNthNode(ll.head, 3);
ll.PrintLL();
}
}
I tried the code that I have posted but it is not printing when n equal size of LL.
The reason is that although your function RemoveNthNode returns the head after the removal, the caller (in main) ignores the returned value, so that it never sees a change to head. The confusion may also be caused by the parameter that has the name head, which shadows the head property of the class instance.
As it is not intuitive that the caller needs to provide head as argument, while you would expect that the method would know what the head of the list is, I suggest to make it a void method which doesn't take the head argument.
You should also take care of the case where head is null.
Your PrintLL has a problem too: it doesn't print the node when the list has just one node.
Corrected code:
public void PrintLL() {
Node n = head;
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
System.out.println("NULL");
}
public void RemoveNthNode(int nth){
if(head == null || head.next==null){
head = null;
return;
}
int size=0;
Node curNode=head;
while(curNode!=null) {
curNode = curNode.next;
size++;
}
if(nth==size){
head = head.next;
return;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
ll.PrintLL();
ll.RemoveNthNode(3);
ll.PrintLL();
}
In this java code as I input 4 integer type numbers in linked list it shows only first 3 as output
so can you guide why is that. I when give only 1 value in linked list it doesn't appear when I give 2 values it shows the first one as output only.
here only output show 4, 34, and 5 but not 50 I don't understand what wrong with code?
enter code here
import java.lang.*;
public class Main{
Node head;
static class Node{
int data;
Node next;
public Node(int d){
data=d;
next=null;
}
}
public void insertFirst(int data)
{
Node n=new Node(data);
n.next=head;
head=n;
}
public void insertLast(int data){
Node n=new Node(data);
if(head==null) {
head = n;
} else{
Node t=head;
while(t.next!=null)
{ t=t.next;}
t.next=n;
}
}
public void display(){
Node n=head;
if(n==null)
System.out.println("empty");
else
{
while(n.next!=null)
{
System.out.print(n.data+" ");
n=n.next;
}
}
}
public static void main(String [] args){
Main m=new Main();
m.insertFirst(34);
m.insertFirst(4);
m.insertLast(5);
m.insertLast(50);
m.display();
}
}
When you reach the last node, node.next == null, you don't print it.
You need to change the condition in your display() method.
Change while(n.next!=null) to while(n != null). The last node has n.next == null, but you should still print it.
Below is my code to print a circular singly linked list from the SECOND NODE(i.e. the node next to my starting node from where I have inserted my values). But it seems that my code is unable to link the last node to my starting node. As a result of which I am not able to print my Circular linked list.
Can somebody correct my mistake?
INPUT: 1 2 3 4
EXPECTED O/P: 2 3 4 1
O/P GETTING: 2 3 4
import java.util.Scanner;
public class CircularLinkedList {
CircularLinkedList ptr,head,next;
int v;
void headcre()
{
head=new CircularLinkedList();
ptr=head;
}
void linkcre(int n)
{
Scanner sc=new Scanner(System.in);
ptr=head;
System.out.println("Enter elements of list");
for(int i=0;i<n;i++)
{
ptr.v=sc.nextInt();
ptr.next=new CircularLinkedList();
ptr=ptr.next;
}
ptr.next=head; //TO LINK LAST NODE TO STARTING NODE
}
void printcre()
{
ptr=head;
ptr=ptr.next; //printing the list from the second node
while(ptr.next!=head)
{
System.out.print(ptr.v+" ");
ptr=ptr.next;
}
}
public static void main(String[] args) {
CircularLinkedList obj=new CircularLinkedList();
System.out.println("Enter number of elements to be present in the list");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
obj.headcre(); //To create starting node
obj.linkcre(n); //To enter elements
obj.printcre(); //To print the list
}
}
Some issues:
Your code is trying to fit two different concepts into one class: a node of a list, and the list itself. It is weird that a first instance of the CircularLinkedList class serves as the container for head, while other instances (which also have a head reference which remains useless) serve as the actual data-nodes of the list. You should dedicate a separate class for each.
The code creates a node before it has a value to store in that node. This means your list will always have a node that is unused for data. So when all input has been stored in nodes, there is one more node that was created, which has no data (ptr.v remains uninitialised).
In printcre, when the head node is visited, the loop exits, and so that node's value is never printed.
It is not good practice to perform I/O in methods of such a class. Keep I/O in your main code, and provided methods that do the pure list stuff, or maybe produce a string representation of the list. But don't do I/O in these methods. Mixing concerns like that is not a good habit.
For a circular list it is actually more interesting to keep a reference to the tail than to the head, because the head can be easily be found from the tail (it is its successor), while getting the tail from the head requires to traverse all nodes.
Here is code I would suggest:
ListNode class
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = this; // Make circular by default
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
CircularLinkedList class
public class CircularLinkedList {
ListNode tail = null;
public void append(int data) {
if (tail == null) {
tail = new ListNode(data);
} else {
tail = tail.next = new ListNode(data, tail.next);
}
}
public String toString() {
if (tail == null) return "";
String s = "";
ListNode node = tail.next.next;
while (node != tail.next) {
s += node.val + " ";
node = node.next;
}
return s + node.val; // Also include the head's value in the string
}
}
Driver code
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements to be present in the list");
int n = sc.nextInt();
CircularLinkedList list = new CircularLinkedList();
System.out.println("Enter elements of list");
for (int i = 0; i < n; i++) {
list.append(sc.nextInt());
}
sc.close();
System.out.println(list.toString());
}
I want to solve some linked list questions but i am not able to take input from console, I don't know where I am doing wrong.
What am I doing wrong with my code :
import java.util.*;
class ScannerInputLinkedList{
static class Node{
int data;
Node next;
}
void insertNode(Node head, int data){
Node curr = head;
Node temp = new Node();
temp.data = data;
temp.next = null;
while(curr.next!=null){
curr = curr.next;
}
curr.next = temp;
System.out.print(curr.data+"->");
}
System.out.println();
public static void main(String[] args) {
ScannerInputLinkedList obj = new ScannerInputLinkedList();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int x;
Node head = new Node();
while(t-- > 0){
x = sc.nextInt();
obj.insertNode(head, x);
}
}
}
Just a small problem with your code. The printing statement (located above main method) is outside any method. In fact it is not needed at all. Just remove it and change System.out.print(...) to System.out.println(...) at line 19. This will make your code free of errors.
This solution was regarding your problem that you weren't able to get inputs. Apart from that, it is unclear what you are trying to achieve. In case you are trying to append nodes to your linked list, you will need to recheck your logic. Your code is creating a list with already a node, appending to it but you are printing the data of node whose next is new node.
For inputs [t = 1, x = 3], your code is printing 0->. This "0" is the data of first node for the set of inputs, and your new node will be the second node.
Anyways, just for the solution to your problem of not being able to take inputs, here is the corrected code. You can use IDE's like netbeans or eclipse to quickly identify what is wrong with your code.
import java.util.*;
class ScannerInputLinkedList{
static class Node{
int data;
Node next;
}
void insertNode(Node head, int data){
Node curr = head;
Node temp = new Node();
temp.data = data;
temp.next = null;
while(curr.next!=null){
curr = curr.next;
}
curr.next = temp;
System.out.println(curr.data+"->");
}
public static void main(String[] args) {
ScannerInputLinkedList obj = new ScannerInputLinkedList();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int x;
Node head = new Node();
while(t-- > 0){
x = sc.nextInt();
obj.insertNode(head, x);
}
}
}
I am learning Linked List in Java and I am trying to add numbers to the tail, say a 10 Numbers. However, after insertion I am only able to retrieve the last two numbers, I don't understand what I am doing wrong. Here is my code:
import java.util.*;
public class LinkTry
{
public static void main(String args[])
{
Scanner sx = new Scanner(System.in);
Node N = new Node();
for(int i=0;i<10;i++)
{
Node last = new Node();
while(N.link!=null)
N=N.link;
last.data = sx.nextInt();
N.link = last;
}
System.out.println("");
for(Node x=N;x!=null;x=x.link)
System.out.print("-->"+x.data);
}
public static class Node
{
int data;
Node link;
}
}
I am having a bit trouble how address is passed on here, an answer that explains the memory addressing in Linked list would be very helpful.
import java.util.Scanner;
public class LinkTry
{
public static void main(String args[])
{
Scanner sx = new Scanner(System.in);
Node first = null;
Node last = null;
for(int i=0;i<10;i++) {
Node current = new Node();
current.data = sx.nextInt();
if (first == null) {
first = current;
last = current;
} else {
last.link = current;
last = current;
}
}
System.out.println("");
for(Node x=first;x!=null;x=x.link)
System.out.print("-->"+x.data);
}
public static class Node
{
int data;
Node link;
}
}
The problem is that this line:
N=N.link;
causes N to no longer point to the head of the list, whereas this line:
for(Node x=N;x!=null;x=x.link)
assumes that N still points to the head of the list.
To fix this, you need to use separate variables — you need to keep separate references to the head of the list (for later reference) and the tail of the list (for appending elements there).
The problem is in the for loop. As you are iterating through the loop you have lost reference to the head of the List you started with i.e., Node N = new Node();
Issue in the for loop, highlighted between ** ** below
for(int i=0;i<10;i++)
{
Node last = new Node();
while(N.link!=null)
N=N.link;
last.data = sx.nextInt();
**N.link = last;**
}
At the end of 10 iterations, now 'N' is pointing to last but one Node. And so it is printing only last 2 items.