Reputation: 29
I couldn't print the linked list it infinitely prints 4 as the value. What is wrong with this code ? In the below code, I am trying to implement a singly linked list after adding every element while am trying to print it infinitely prints 4 as output any idea why?
import java.util.*;
class Linkedit{
static class Node{
static Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
Node head=null;
public void insert(int data){
Node k=new Node(data);
k.next=head;
head=k;
}
public void show(){
Node a=head;
while(a!=null){
System.out.println(a.data);
a=a.next;
}
}
public static void main(String args[]){
Linkedit g=new Linkedit();
g.insert(3);
g.insert(4);
g.insert(5);
g.show();
}
}
Upvotes: 1
Views: 939
Reputation: 393771
Here's the problem:
static Node next;
The next
member should not be static, since each Node
should have a different next
value.
Changing
static class Node {
static Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
to
static class Node {
Node next;
int data;
Node(int t){
data=t;
next=null;
}
}
Solves your problem.
Upvotes: 4