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();
}
}
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.
Related
I am trying to find a way to write a java program with recursion logic for insertion, searching as well as traversal for singly linked list. But, I don't know how I can do it while my head node is private. Here is the piece of code I have written :
class Node {
int data;
Node next;
}
public class SingleList {
private Node head;
public SingleList() {
head = null;
}
void insert(Node temp, int num, int n) {
//Suggest some code here
}
boolean search(Node temp, int num) {
//Suggest some code here
}
void traverse(Node temp) {
//Suggest some code here
}
}
You don't have any problem to access the head from your class.
In addition, the Node class is probably irrelevant for any other class other than SingleList class, it will be a better idea to include it within the SingleList class
public class SingleList {
private class Node {
int data;
Node next;
}
// Rest of your class code...
}
I need to implement a Node class, where the basic methods are: getItem(), getNext(), setItem() and setNext(). I want the nodes to be able to store at least the default integer range in Java as the “item”; the “next” should be a reference or pointer to the next Node in a linked list, or the special Node NIL if this is the last node in the list.I also want to implement a two-argument constructor which initializes instances with the given item (first argument) and next node (second argument) , I've kind of hit a brick wall and need some guidance about implementing this , any ideas ?
I have this so far:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
While implementing the custom LinkedList/Tree, we need Node. Here is demo of creating Node and LinkedList. I have not put in all the logic. Just basic skeleton is here and you can then add more on yourself.
I can give you a quick hint on how to do that:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
You can create a Node object by calling:
Node newNode = Node(2);
This is not a complete solution for your problem, the two parameter constructor and the last node link are missing, but this should lead you in the correct direction.
Below is a simple example of the Node implementation, (i renamed Item to Value for readability purpose). It has to be implemented somehow like this, because methods signatures seems to be imposed to you. But keep in mind that this is definely not the best way to implement a LinkedList.
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
The node class that will be implemented changes according to the linked list you want to implement. If the linked list you are going to implement is circular, then you could just do the following:
public class Node {
int data;
Node next = null;
public Node(int data){
this.data = data;
}
}
Then how are you going to implement the next node?
You are going to do it in the add method of the circularLinkedList class. You can do it as follows:
import java.util.*;
public class CircularLinkedList {
public CircularLinkedList() {}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
tail.next = head;
}
public void displayList() {
System.out.println("Nodes of the circular linked list: ");
Node current = head;
if(head == null) {
System.out.println("Empty list...");
}
else {
do {
System.out.print(" " + current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}
}
I want to insert a Node in to the middle of a doubly linked list.This is my implementation.
My default argument is the node before the to-be inserted node .
public class DListNode{
public DListNode prev,next;
public Object item;
public DListNode(Object i,DListNode n,DListNode p){
prev=p;
next=n;
item=i;
}
public DListNode(Object i){
this(i,null,null);
}
}
public void insertAfter(Object e,DListNode firstNode) throws UnderFlow{
if(isEmpty()||(head==tail))
throw new UnderFlow("need at least two nodes");
else{
DListNode v=firstNode.next;
DListNode k=new DListNode(e,v,firstNode);
firstNode =k;
v.prev=k;
}
}
public static void main (String args[]) throws UnderFlow{
DList d=new DList();
d.insertFront("d");
d.insertFront("b");
d.insertAfter("c",d.head);
System.out.println(d.toString());
}
Though I can't see where I am making the mistake it only prints out b,d.
c is not inserted in the middle.
Please can someone point out where I am making the mistake
I would suggest you to use variable names with some meaning. Your names like k, v are terrible to understand
Instead of firstNode =k; should be firstNode.next =k; but it's better to rewrite with proper names. Like this
DListNode next=firstNode.next;
DListNode newOne=new DListNode(e,next,firstNode);
firstNode.next =newOne;
next.prev=newOne;
I need write a method to loop through a linked list searching to see if Object data is in linked list. Any help?
public class LinkedList {
private LinkedListNode head;
public boolean find(Object data){
for(somethinggoeshere..){
if(head==data){
return true;
}else{
return false;
}
}
Any help?
Edit: My LinkedListNode class:
public class LinkedListNode {
private Object data;
private LinkedListNode next;
public LinkedListNode(Object data, LinkedListNode next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public LinkedListNode getNext() {
return next;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
}
Edit: Final solution for those who are interested:
public class LinkedList {
private LinkedListNode head;
public boolean find(Object data){
LinkedListNode temp = head;
while(temp!= null) // check if you have reached the tail
{
if(data.equals(temp.getData()))
{
return true;
}
temp = temp.getNext(); // move to the next node
} // end of while loop
return false;
} // end of find method
Assuming that you wrote the code for LinkedListNode, you should know wether or not is Iterable, and thus be able to loop through it with a for-each loop like that.
As it stands, you should traverse the nodes either recursively or in an iterative manner, by using some form of "next" pointers that is held within each node, and in essence do a linear search through the links until you find the data you are looking for, or return null.
Here's a link for some help on implementing a linked list:
http://www.danielacton.com/Data-Structures/Linked-List/Java/
You need to loop through your LinkedList and search for the data. If you reach tail of the list and still unable to find the data this implies that data is not in the LinkedList.
I am assuming that LinkedListNode has a member variable data to store the data in each node. Below is the corrected code :
public class LinkedList {
private LinkedListNode head;
public boolean find(Object data)
{
LinkedListNode temp = head;
while(temp!= null) // check if you have reached the tail
{
if(data.equals(temp.getData()))
{
return true;
}
temp = temp.getNext(); // move to the next node
} // end of while loop
return false;
} // end of find method
}
Ok i am trying to write a program for binary search tree. Everything looks good except my program keeps printing this instead of just my inorder traversal of integers.I tried to just just println in the main method and got the same thing?
This is my code:
public class bst {
Node root;
public Node getRoot(){
return root;
}
public bst(){
root=null;
}
//method addNode
public void insert(int key){
Node newNode= new Node(key);//initialize Node
if(root==null){
root=newNode;
}else{
Node focusNode=root;
Node insNode=root;
while(insNode!=null){
focusNode=insNode;
if(key<focusNode.getKey()){
insNode=insNode.getLeft();
}
else{
insNode=insNode.getRight();
}
}
if(key<focusNode.getKey()){
focusNode.setLeft(newNode);
}
else{
focusNode.setRight(newNode);
}
}
}
public void inOrder(Node focusNode){
if (focusNode !=null){
inOrder(focusNode.leftChild);
System.out.println(focusNode);
inOrder(focusNode.rightChild);
}
}
//Node class
class Node{
int key;
Node leftChild;
Node rightChild;
//Node constructor
Node(int key){
this.key=key;
leftChild=null;
rightChild=null;
}
public void setLeft(Node left){
this.leftChild=left;
}
public void setRight(Node right){
this.rightChild=right;
}
public Node getLeft(){return leftChild;}
public Node getRight(){return rightChild;}
public void setKey(int k){this.key=k;}
public int getKey(){return key;}
public void print(){
System.out.println(getKey());
}
}
public static void main(String[] args){
bst theTree= new bst();
theTree.insert(30);
theTree.insert(60);
theTree.insert(50);
theTree.insert(70);
theTree.inOrder(theTree.getRoot());
}
}
In the inOrder method, you do:
System.out.println(focusNode);
You are printing focusNode directly, so unless your Node class overrides the default toString method you will just see a hash code of your object (see this question for details if you are interested). You probably wanted something like
System.out.println(focusNode.getKey());
or simply using the print method you wrote instead.
It looks like you are trying to print the actual Node, which will just be the memory address that of that node. If you want to print the the integers, you should print the key to the node.
print(node.getKey());