I am trying to implement linked list in java, but nothing gets printed out. I tried debugging it and it seems that every time the Add function gets called the previous value gets over written. However when i check the logic of it, it should work.
public class MyLinkedList {
public Node head;
public Node curr;
public MyLinkedList() {
// TODO Auto-generated constructor stub
head = null;
curr = null;
}
public void Add(int data) {
Node box = new Node();
box.data = data;
box.next = null;
curr = head;
if (curr == null) {
head = box;
curr = null;
}
else {
while (curr.next != null) {
curr = curr.next;
}
curr.next = box;
}
}
public void Print() {
curr = head;
while (curr != null) {
System.out.println(curr.data);
curr = curr.next;
}
}
}
This is what the Node class has
public class Node {
public int data;
public Node next;
}
Your code is fine. Just go and delete *.class files. It may be stuck in early stages of your code.
*.class files located under output folder (name of the folder can change depending on the IDE you used but generally under build folder.) you may need to delete that folder completely.
It works already, but I'll tidy it up for you:
public class MyLinkedList {
private Node head; //never expose a field as public
//the whole constructor was unnecessary
public void add(int data) { //methods start with a lower case
add(new Node(data)); //nodes always need data, so I'm passing in constructor
}
// this method adds an existing node rather than the previous add both
// creating, finding the end and adding
private void add(Node node) {
if (head == null) {
head = node;
} else {
lastNode().next = node;
}
}
private Node lastNode() { //finds the last node in the chain
Node curr = head; //curr is local
while (curr.next != null) {
curr = curr.next;
}
return curr;
}
public void print() { //methods start with a lower case
Node curr = head; //curr is local
while (curr != null) {
System.out.println(curr.data);
curr = curr.next;
}
}
private static class Node { //this class is just useful internally to MyLinkedList
private final int data; //final - node data doesn't change
private Node next;
private Node(int data) {
this.data = data;
}
}
}
Related
I am using custom made data structure and, in this project, I am using a doubly LinkedList to implement a blockchain.
so I have made a Main class and a Block class and of course the LinkedList class, the LinkedList class was made to accept data of the type Block so when I try to add elements to my list i pass on a new block with the information the problem is after the first element I don't know how to call the hash value of the previous block.
basically in every block class there should be a hash and the hash of the previous block in block one there is no prev hash so its 0 but the second block and onwards is where I am lost.
this is my block class
import java.util.Date;
public class Block {
public String hash;
public String previousHash;
private String data;
private long timeStamp;
public Block(String data, String previousHash) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}
public String calculateHash() {
String calculatehash = StringUtil.applySha256(
previousHash + Long.toString(timeStamp) + data);
return calculatehash;
}
}
this is my doubly LinkedList file
class Node {
private Block data; // node storing int data
private Node nextNode; // the next pointer node, the arrow in drawing
private Node prevNode;
// don't forget the class constructor
public Node(Block data2) {
this.data = data2;
}
// since we made variable private
// to access them we need setters and getters
public Block getData() {
return this.data;
}
public Node getNextNode() {
return this.nextNode;
}
public Node getPrevNode() {
return this.prevNode;
}
public Block setData(Block data) {
return this.data = data;
}
public Node setNextNode(Node nextNode) {
return this.nextNode = nextNode;
}
public Node setpervNode(Node prevNode) {
return this.prevNode = prevNode;
}
#Override
public String toString() {
return "Data: " + this.data;
}
}
public class DoublyLinkedlist {
private Node head;
private Node tail;
private int size = 0;
public DoublyLinkedlist() {
}
public int getSize() {
return this.size;
}
public void addFirst(Block data) {
Node node = new Node(data);
if (this.tail == null && this.head == null) {
this.tail = node;
this.head = node;
} else if (this.head == null) {
this.head = node;
} else {
Node old = this.head;
node.setNextNode(old);
this.head = node;
old.setpervNode(this.head);
}
this.size++;
}
public void addLast(Block data) {
Node node = new Node(data);
if (this.tail == null && this.head == null) {
this.tail = node;
this.head = node;
} else if (this.tail == null) {
this.tail = node;
} else {
Node old = this.tail;
this.tail.setNextNode(node);
this.tail = node;
this.tail.setpervNode(old);
}
this.size++;
}
public Node removeFirst() {
Node removed = this.head;
this.head = this.head.getNextNode();
this.size--;
return removed;
}
#Override
public String toString() {
String output = "[size=" + this.size + "] >> ";
Node fromHead = this.head;
while (fromHead != null) {
output = output + fromHead.getData();
if (fromHead != this.tail)
output = output + " >> ";
fromHead = fromHead.getNextNode();
}
output += "\n";
Node fromTail = this.tail;
while (fromTail != null) {
output = output + fromTail.getData();
if (fromTail != this.head)
output = output + " << ";
fromTail = fromTail.getPrevNode();
}
return output;
}
public boolean contains(Block data) {
Node current = this.head;
while (current != null) {
if (current.getData() == data) {
return true;
}
current = current.getNextNode();
}
return false;
}
public void clear() {
while (this.head != null) {
this.removeFirst();
}
System.out.println("List Is Cleared!");
}
}
and this is my Main class
public class Main {
public static DoublyLinkedlist blockchain = new DoublyLinkedlist();
public static void main(String[] args) {
blockchain.addFirst(new Block("hi i am the first block", "0"));
blockchain.addLast(new Block("yo i am the second block", blockchain.get(blockchain.getSize()-1.hash)));
}
}
i tried using the get method based on a tutorial that was implementing using an arraylist but obviously it's a wrong syntax.
The main program should not have to deal with retrieving hashes, not even with creating blocks. Instead aim for your main code to look like this:
public class Main {
public static DoublyLinkedlist blockchain = new DoublyLinkedlist();
public static void main(String[] args) {
blockchain.addLast("Hi, I am the first block");
blockchain.addLast("Yo, I am the second block");
}
}
Then your other classes would also need some adaptations. In Node I would add a constructor that can take a second argument, so it can establish the link with a previous node:
public Node(Block data, Node prevNode) { // Additional constructor
this.data = data;
this.prevNode = prevNode;
if (prevNode != null) {
prevNode.setNextNode(this);
}
}
In the DoublyLinkedList class, remove the addFirst method: you don't want to add blocks before any existing blocks, as that would invalidate the hashes of the blocks that are already in the list. Blocks should only be added at the end.
The addLast method should take a string instead of a Block instance, and this method can also be used for adding the very first block.
public void addLast(String data) {
tail = new Node(new Block(data, tail != null ? tail.getData().hash : "0"), tail);
if (head == null) head = tail;
size++;
}
When I create a Node object and call "appendToTail" the Node object has a sequence of nodes via the next attribute (as expected). I tried creating a pop, where it takes the head (aka 'this') and reference it with a variable and overwrite it with its next. However, 'this' remains the same as the original head. What am I doing wrong, or is there no way to modify 'this'?
public class Node {
Node next = null;
int data;
public Node(int d) {
data = d;
}
public void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
public void popHead() {
Node n = this;
n = n.next;
}
}
Basically you need to construct a custom List and add each node at End. Also you need to store first node in order to have the starting point for looping.
public class NodeList
{
Node head=null;
public static void main(String args[])
{
NodeList nl = new NodeList();
nl.addNode(1);
nl.addNode(2);
nl.addNode(3);
nl.listNodes();
}
public void addNode(int data)
{
if(head==null)
{
head = new Node(data);
}
else
{
Node curent = head;
while(curent.next != null)
{
curent = curent.next;
}
curent.next = new Node(data);
}
}
public void listNodes()
{
if(head !=null)
{
Node curent = head;
System.out.println(curent.data);
while(curent.next !=null)
{
curent = curent.next;
System.out.println(curent.data);
}
}
}
class Node
{
Node next = null;
int data;
public Node(int d) {
data = d;
}
}
}
Output
1
2
3
I'm trying to add several information into one Node in a singly linked list... How do I do that?
After asking the user for several vehicle information: plateNo(String), vehicleType(String), serviceType(String) I will have to store this information for each vehicle. I have to use a singly linked list to store all the vehicle entering and leaving the wash.
Then, my program should display all the vehicles entering and leaving the vehicle wash with their service order.
How do I do this?
This is my singly LinkedList:
public class LinkedList<T>
{
private Node<T> head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void displayList(){
Node<T> current = head; // start at beginning
while(current != null) // until end of list,
{
System.out.print(current.getData() + " ");
current = current.getNext();
//move to next link
}
System.out.println("");
}
public Node deleteFront()
{
Node<T> temp = head;
if(head.getNext() == null) // if only one item
return null; // return null
head = head.getNext(); // first --> old next
count--;
return temp;
}
public void removeValue(T value)
{
Node<T> current = head, prev = null;
while (current != null)
{ //if current node contains value
if (value == current.getData())
{
//handle front removal (case 1)
if( prev == null)
head = current.getNext();
else //handle mid removal (case 2)
prev.setNext(current.getNext());
// prev node now points to maxNode's (a.k.a current) successor, removing max node.
break; // remove first occurence only
}
// update prev to next position (curr)
prev = current;
// move curr to the next node
current = current.getNext();
}
}
public void addFront(T n)
{
Node<T> newNode = new Node<T>(n);
newNode.setNext(head);
head = newNode;
count++;
}
}
My Node
public class Node<T> {
private T data;
private Node next;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(T data) {
this.data = data;
this.next = null;
}
}
I'm trying to add several information into one Node in a singly linked list... How do I do that?
... by thinking object-oriented! Create a class that models a vehicle:
class Vehicle {
String plateNo;
String vehicleType;
String serviceType;
// constructors, getters, setters, other methods ...
}
You have already a generic Node<T>, so use it:
Vehicle vehicle = callAwesomeMethodThatCreatesVehicleInstance();
Node<Vehicle> node = new Node(vehicle);
Now you can use such a node in your linked list.
Your code seems fine. You just need to define a new class that contains all the information that you want to store. As you have already made the Node class for a generic data type T, you can then insert the new class that you will make here.
class Details{
String plateNo;
String vehicleType;
String serviceType;
public Details(){
this.plateNo = "";
this.vehicleType = "";
this.serviceType = "";
}
}
Then in your code for the linked list:
public class LinkedList<T>
{
private Node<Details> head = new Details();
//rest of the class
}
My problem is in the add method. I think I know what I want it to do but I can't figure out what type of loop I should use to look through the list. As you can see I started to make a if else loop but I couldn't figure out what I should use as the counter. I'm pretty sure I have the right logic in dealing with the add but I feel like I'm not quite there yet. I was thinking of using compareTo in some fashion.
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node topNode;
private class Node
{
private E data;
private Node nextNode;
public Node(E data)
{
this.data = data;
nextNode = null;
}
}
public OrderedLinkedList()
{
topNode = null;
}
public boolean empty()
{
if(topNode == null)
return true;
return false;
}
public String toString()
{
String myString = "";
Node nextNode = topNode;
while(nextNode != null)
{
myString = topNode + " -> " + nextNode;
nextNode = topNode.nextNode;
}
return myString;
}
public void add(E data)
{
Node myNode = new Node(data);
Node priorNode = topNode;
Node currentNode = topNode;
if(___)
{
priorNode = currentNode;
currentNode = currentNode.nextNode;
}
else
{
priorNode.nextNode = myNode;
myNode.nextNode = currentNode;
}
}
}
Since you don't typically know the length of a linked list until you've walked down it, the usual thing would be to use a while loop (as you've done in your toString() method)
Perhaps using a doubly linked list would be more beneficial. Consider the following alterations to your class:
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node head;
private Node tail;
private class Node
{
private E data;
private Node nextNode;
private Node prevNode;
public Node(E data)
{
this.data = data;
nextNode = null;
prevNode = null;
}
public void setNext(Node node)
{
this.nextNode = node;
}
public Node getNext()
{
return this.nextNode;
}
public void setPrev(Node node)
{
this.prevNode = node;
}
public Node getPrev()
{
return this.prevNode;
}
public E getData()
{
return this.data;
}
public int compareTo(Node that) {
if(this.getData() < that.getData())
{
return -1;
}
else if(this.getData() == that.getData()
{
return 0;
}
else
{
return 1;
}
}
}
public OrderedLinkedList()
{
head = new Node(null);
tail = new Node(null);
head.setNext(tail);
tail.setPrev(head);
}
public boolean empty()
{
if(head.getNext() == tail)
{
return true;
}
return false;
}
public void add(E data) {
Node tmp = new Node(data);
if(this.empty()) {
this.addNodeAfterNode(tmp, head);
} else {
Node that = head.getNext();
// this while loop iterates over the list until finding the correct
// spot to add the new node. The correct spot is considered to be
// when tmp's data is >= that's data, or the next node after 'that'
// is tail. In which case the node is added to the end of the list
while((tmp.compareTo(that) == -1) && (that.getNext() != tail)) {
that = that.getNext();
}
this.addNodeAfterNode(tmp, that);
}
}
private void addNodeAfterNode(Node addNode, Node afterNode)
{
addNode.setNext(afterNode.getNext());
afterNode.getNext().setPrev(addNode);
afterNode.setNext(addNode);
addNode.setPrev(afterNode);
}
}
Trying to implement single-linked-list in below program, i am really not able to undertsand how to add a node in an Linked list (for start, m trying it on empty linked list).
To put it plain simple,i tried to setData and setNext but getSizeofList() return 0 everytime....its really looking like a rocket science to me now!!
Question : Can some-one tell me how to implement it....or rather, add a node to existing linked list....
What i have tried so far and why they dint worked out: i referenced multiple programs but they were too complex for me to understand(rocket science), so wrote below program from what i understood from algorithms....but even in algo's, they just show methods on how to implement and this is where i failed, as, i dont understand,what data-type and value is to be passed for adding a node...
please not that m not a java guy, so please go easy, this question comes in as an attempt to learn
package Data_S;
public class Linked_List {
private int data;
private Linked_List next_ptr;
private Linked_List headNode = null;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Linked_List ll = new Linked_List();
//ll.setnext(25);
ll.insert_node(24);
ll.traverse();
ll.getSizeofList();
}
//size of list
public void getSizeofList()
{
int l = 0;
Linked_List curr = headNode;
while(curr != null)
{
l++;
curr = curr.getnext();
}
System.out.print("Size of list is = "+l);
}
//insert node
public void insert_node(/*Linked_List node, */int data)
{
if(headNode == null)
{
System.out.println("in insert"); // checking
this.setnext(headNode);
this.setData(data);
System.out.print("value = "+this.getData());
}
}
//set data for this node
public void setData(int data)
{
this.data = data;
}
//return the data
public int getData()
{
return this.data;
}
//set next pointer
public void setnext(Linked_List next_ptr)
{
this.next_ptr = next_ptr;
}
//get next pointer
public Linked_List getnext()
{
return this.next_ptr;
}
}
You have to make a distinction between the single chains (Node) of a linked list, and the entire container (LinkedList).
public class LinkedList {
Node head;
int size; // Maybe
public void insertAtEnd(int data) {
Node previous = null;
for (Node current = head; current != null; current = current.next) {
previous = current;
}
Node baby = new Node(data);
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
public void insertInSortedList(int data) {
Node previous = null;
Node current = null;
for (current = head; current != null && data < current.data;
current = current.next) {
previous = current;
}
Node baby = new Node(data);
baby.next = current;
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
One may sometimes see encapsulation as:
public class LinkedList {
private static class Node {
}
...
}
You never set headnode. In insertnode you just use setnext which does not set headnode. You are mixing the top class and the node implementation together.
Here is an example of how to implement a linked list in java for further reference:
How do I create a Linked List Data Structure in Java?