Add nodes in linked list - java

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?

Related

how do I call the previous Node of an unknow object?

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

How to modify the head of a LinkedList without a wrapper class?

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

Implementing Linked List in java

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

Storing more than one information into one Node in a singly linked list

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
}

MergeSorting LinkedList in Java recursively

So the task is to implement a linked-list and merge-sort which sorts linked-lists. I am fully aware that in industry I most likely won't have to implement any of these but I feel it's a good way to practice Java. Here is what I've got up to this point:
Node class:
public class Node<E extends Comparable<E>>
{
public E data;
public Node<E> next;
public Node(E data)
{
this.data = data;
next = null;
}
public void printData()
{
System.out.print(data + " ");
}
}
LinkedList class:
public class LinkedList<E extends Comparable<E>>
{
protected Node<E> root;
protected int size = 0;
public LinkedList()
{
root = null;
}
public void addBeg(E e)
{
Node<E> newNode = new Node<E>(e);
newNode.next = root;
root = newNode;
size++;
}
public Node deleteBeg()
{
Node<E> temp = root;
if(!isEmpty())
{
root = root.next;
size--;
}
return temp;
}
public void setRoot(Node<E> newRoot)
{
root = newRoot;
}
public boolean isEmpty()
{
return root == null;
}
public Node<E> getRoot()
{
return root;
}
public void printList()
{
Node<E> cur = root;
while(cur!=null)
{
cur.printData();
cur=cur.next;
}
System.out.println();
}
}
MergeSorter Class:
public class MergeSorter<E extends Comparable<E>>
{
public MergeSorter()
{
}
private void split(LinkedList<E> list, LinkedList<E> firHalf, LinkedList<E> secHalf)
{
//if 0 or only 1 elements in the list - it doesn't seem to work, however
if(list.getRoot() == null || list.getRoot().next == null)firHalf = list;
else{
Node<E> slow = list.getRoot();
Node<E> fast = list.getRoot().next;
while(fast!=null)
{
fast = fast.next;
if(fast!=null)
{
fast = fast.next;
slow = slow.next;
}
}
//If I use the following line firHalf list is empty when in the caller of this method (it's not in this method, however). Don't understand why ):
//firHalf = list;
firHalf.setRoot(list.getRoot());
secHalf.setRoot(slow.next);
slow.next = null;
}
}
private LinkedList<E> merge(LinkedList<E> a, LinkedList<E> b)
{
LinkedList<E> mergedList = new LinkedList<E>();
Node<E> dummy = new Node<E>(null);
Node<E> tail = dummy;
while(true)
{
if(a.getRoot() == null){
tail.next = b.getRoot();
break;
}
else if(b.getRoot() == null){
tail.next = a.getRoot();
break;
}
else
{
if(a.getRoot().data.compareTo(b.getRoot().data) <= 0)
{
tail.next = a.getRoot();
tail = tail.next;
a.setRoot(a.getRoot().next);
}
else
{
tail.next = b.getRoot();
tail = tail.next;
b.setRoot(b.getRoot().next);
}
tail.next = null;
}
}
mergedList.setRoot(dummy.next);
return mergedList;
}
public void mergeSort(LinkedList<E> list)
{
Node<E> root = list.getRoot();
LinkedList<E> left = new LinkedList<E>();
LinkedList<E> right = new LinkedList<E>();
if(root == null || root.next == null) return; //base case
split(list, left, right); //split
mergeSort(left);
mergeSort(right);
list = merge(left, right); // when this mergeSort returns this list should be
// referenced by the left or right variable of the
// current mergeSort call (but it isn't!)
}
}
I am fairly new to Java (coming from a C background) so I am sincerely sorry in advance if my code is utterly false. When I test the split and merge methods in the MergeSorter class independently, everything seems to work (splitting a list consisting of 0 or 1 element is not working and is driving me crazy but this is not needed for merge-sorting). The mergeSort method, however, is not working and I can't seem to figure out way. I tried to debug it myself and there's seems to be a problem when two halves are merged into one list and then the recursion returns. The newly merged list should be referenced by either the left or right variable of the current mergeSort call but instead I get only the last element instead of the whole list.
Method arguments in Java are always passed by value.
This can be a bit confusing, since objects are always accessed via references, so you might think they're passed by reference; but they're not. Rather, the references are passed by value.
What this means is, a method like this:
public void methodThatDoesNothing(Object dst, Object src) {
src = dst;
}
actually does nothing. It modifies its local variable src to refer to the same object as the local variable dst, but those are just local variables that disappear when the function returns. They're completely separate from whatever variables or expressions were passed into the method.
So, in your code, this:
firHalf = list;
does not really do anything. I guess what you want is:
while (! firHalf.isEmpty()) {
firHalf.deleteBeg();
}
if (! list.isEmpty()) {
firHalf.addBeg(list.root().data);
}
which modifies the objected referred to by firHalf so it has the same zero-or-one elements as list.

Categories