Adding at the End - java

Thank you for taking the time to read this, I'm currently taking a Java class and the professor told us that a good practice to understand links would be to make a doubly linked list. I have made a singly linked list but I am having trouble converting it to a doubly linked list. The problem I am having is I'm trying to add a number to the end of the list but when I try to add a new number to the end it just shows that numbers and not the others. I think I'm just creating a new list and displaying that but I'm not sure. An example of code would be really appreciated.
Normal Add Code:
public void add(int element){
Node n = new Node();
n.setItem(element);
n.setNext(head);
n.setBefore(null);
if(head != null) {
head.setBefore(n);
}
head = n;
}
The add to last code:
public void addLast(int element) {
Node currentNode = head;
currentNode.setItem(element);
currentNode.setBefore(tail);
currentNode.setNext(null);
tail = currentNode;
}
FULL CODE:
public class DoubleLink {
private Node head;
private Node tail;
//Methods
//Constructors
public DoubleLink(){
head = null;
tail = null;
}
public void add(int element){
Node n = new Node();
n.setItem(element);
n.setNext(head);
n.setBefore(null);
if(head != null) {
head.setBefore(n);
head = n;
}
public void display(){ //LIST TRAVERSAL!
// Reference traversal
//Needed an interatior
Node currentNode = head;
while(currentNode != null){
System.out.print(currentNode.getItem()+ " ");
currentNode = currentNode.getNext();
}
System.out.println();
}
public int search(int element){
int position = 0;
Node currentNode = head;
while(currentNode != null){
if(currentNode.getItem() == element){
return position;
}
position++;
currentNode = currentNode.getNext();
}
return -1;
}
public void insert(int element, int position){
int currentposition = 0;
Node currentNode = head;
//Traverse to the right position
while(currentposition < position-1){
currentposition++;
}
Node n = new Node();
n.setItem(element);
n.setNext(currentNode.getNext());
currentNode.setNext(n);
//The previous number connecting to the new number
currentNode = tail;
}
public void remove(int position){
int currentposition = 0;
Node currentNode = head;
//Traverse to the right position
while(currentposition < position-1){
currentposition++;
}
Node dyingNode = currentNode.getNext();
currentNode.setNext(dyingNode.getNext());
}
public void addLast(int element) {
Node nodeToInsert = new Node();
nodeToInsert.setItem(element);
nodeToInsert.setBefore(tail);
nodeToInsert.setNext(null);
if(tail != null)
tail.setNext(nodeToInsert); //link the list
tail = nodeToInsert; //now the tail is the new node i added
if(head == null) // if the list has no elements then set the head
head = nodeToInsert;
}
public static void main(String[] args) {
DoubleLink l = new DoubleLink();
l.add(1);
l.add(2);
l.add(3);
l.display();
l.addLast(99);
l.display();
}
}
Node Class:
public class Node {
//Data
private int item;
private Node next;
private Node before;
//Methods
public int getItem(){
return item;
}
public void setItem(int item){
this.item = item;
}
public Node getNext(){
return next;
}
public void setNext (Node next){
this.next = next;
}
public Node getBefore(){
return before;
}
public void setBefore(Node before){
this.before = before;
}
}

You should change your code, creating a new Node() like this.
public void addLast(int element) {
Node nodeToInsert = new Node();
nodeToInsert.setItem(element);
nodeToInsert.setBefore(tail);
nodeToInsert.setNext(null);
if(tail != null)
tail.setNext(nodeToInsert); //link the list
tail = nodeToInsert; //now the tail is the new node i added
if(head == null) // if the list has no elements then set the head
head = nodeToInsert;
}
UPDATE
The problem is in your add method , you are not setting never tail
public void add(int element){
Node n = new Node();
n.setItem(element);
n.setNext(head);
n.setBefore(null);
if(head != null)
head.setBefore(n);
else{
tail=n; // if head == null then now you have an element so head = tail
}
head = n;
}

Try this :
public void addLast(int element) {
Node newNode = new Node();
newNode.setItem(element);
newNode.setNext(null);
newNode.setBefore(tail);
tail.setNext(newNode);
tail = newNode;
}

In addlast(int element) you are not creating memory for new node you just overwriting in the
head node.
So, your code goes like this
public void addlist(int element)
{
Node currentNode = new node();
currentNode.setItem(element);
currentNode.setBefore(tail);
currentNode.setNext(null);
if(tail!=null)
tail.setNext(currentNode);
tail = currentNode;
}

Related

getting no desired output on printing down the LinkedList in revers form

I wrote down the code to print the list in reverse form and after I found that I am not getting desired output, as per my thinking It should work, but it doesn't. after checking a lot of time I tried to find the problem but still getting no output.
Don't compare the code with the complexity because I know the complexity is not well. This is just an idea to bring up the all possible outcomes.
Here is the code:
import java.util.*;
public class printReverse {
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
static class SinglyLinkedList {
public Node head;
public Node tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
}
// Insert the node to the LinkedList method
static void add (Node head, int data) {
Node node = new Node(data);
Node current = head;
if (head == null) {
head = node;
}
else {
current.next = node;
}
current = node;
}
// ArrayList insertion
static void insert (Node head, ArrayList<Integer> a) {
Node current = head;
while (current != null) {
a.add(current.data);
current = current.next;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
SinglyLinkedList list = new SinglyLinkedList();
int n = scan.nextInt();
for (int j = 0; j < n; j++) {
int value = scan.nextInt();
add(list.head, value);
}
ArrayList<Integer> array = new ArrayList<>();
insert(list.head, array);
// Printing ArrayList revsrse
System.out.println(array);
}
scan.close();
}
}
The problem is not adding the node value to the linked list to the (add) method.
code needed a few changes.
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
public Node head;
public Node tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
// Insert the node to the LinkedList method
public void add (Node node) {
if (node != null) {
head.next = node;
head = node;
}
if (tail == null) {
tail = node;
}
}
public void print (Node node) {
if (node.next != null) {
print(node.next);
}
System.out.println(node.data);
}
}
in the main method you can call add method alone if you want to add any node to the list.
SinglyLinkedList list = new SinglyLinkedList();
this code should be out side of the loops because you want a single linked list, if you want to have multiple single linked lists then you can have them inside a loop.
to print the list elements you can traverse all the nodes from tail and print the data with in it. you cannot traverse back from head as head doesn't contain previous node reference.

Why am I not able to remove first node from the linked list with this code?

Below is my method that shows how I am trying to delete a node from linked list. Added complete implementation, including the node and how I am creating the linkedlist.
class Node {
int val;
Node next;
Node(int n){
this.val = n;
}
}
Public class LinkedList {
public static void main(String[] args) {
int[] inp = {100,3,1,50,25};
Node head = createLinkedList(inp);
displayList(head);
System.out.println("List after the node is removed:");
removeNode(head,100);
displayList(head);
}
static void removeNode(Node head, int val) {
Node sentinal = new Node(-1);
sentinal.next = head;
Node prev = sentinal;
while(head!=null){
if(head.val==val){
prev.next = head.next;
return;
}
prev=head;
head=head.next;
}
}
static Node createLinkedList(int[] inp){
Node head = new Node(-1);
Node temp = head;
for(int n:inp){
temp.next = new Node(n);
temp = temp.next;
}
return head.next;
}
}
You're trying to remove the first node? then why not do it this way.
I don't know your code structor but this can help you:
public void RemoveFirst() {
this.Head = Head.Next();
this.Size -= 1;
}
always remember to keep track of the size of the list

Most efficient way to remove a node on a single linked list?

I am implementing a single linked list of integer and I was wondering what is the most efficient way to locate a given value and remove it from the list. This is what I have so far:
public class LinkedList {
Node head;
public void insert(int value){
Node newNode = new Node();
newNode.data = value;
newNode.next = null;
if(head==null){
head = newNode;
} else {
Node iterator = head;
while(iterator.next!=null){
iterator = iterator.next;
}
iterator.next = newNode;
}
}
public void display(LinkedList list){
Node iterator = head;
while (iterator!=null){
System.out.println(iterator.data);
iterator = iterator.next;
}
}
public void remove(LinkedList list, int value){
Node iterator = head;
while(iterator!=null){
if(iterator.next.data == value){
iterator.next = iterator.next.next;
} else{
iterator = iterator.next;
}
}
}
}
public class Node {
int data;
Node next;
}
I am adding snippet here to remove the node from SinglyLinkedList. I prefer forLoop over while; that's the reason I have added snippet with for loop.
Hope the comment in the code helps you to navigate/dry run the snippet.
public boolean remove(int value){
Node oneBeforeValueNode;
// Using for to iterate through the SinglyLinkedList
// head → is the head of your SingleLinkedList
for (Node node = head; node != null; node = node.next) {
// Compare the value with current node
if (value.equals(node.data)) {
// if matches then unlink/remove that node from SinglyLinkedList
// if its a first node in SingleLinkedList
if(oneBeforeValueNode==null){
// Considering there exists next element else SLL will be empty
head = head.next;
} else {
// if there exists next element it SLL it will attach that element with previous one
oneBeforeValueNode.next = node.next;
}
return true;
}
// Storing previous node from current
// To use it once value is found to reference it to current.next(node.next)
oneBeforeValueNode = node;
}
return false;
}
Adding with while variant as well; just to go with your flow.
public Node remove(Node head, int key) {
Node current = head;
Node previous = null;
while (current != null) {
if(current.data == key) {
if(current == head) {
head = head.next;
current = head;
} else {
previous.next = current.next;
current = current.next;
}
} else {
previous = current;
current = current.next;
}
}
return head;
}

LinkedList Insert Last

I am trying to insert element at the end of a linked list insertAtEnd(). When I debug the code I see a node(0,null) is being inserted as default in the beginning of the insertion. I think this is causing the problem while iterating through the list. Any suggestions on how fix this?
package com.ds.azim;
public class Node {
//Node has 1. Data Element 2. Next pointer
public int data;
public Node next;
//empty constructor
public Node(){
//
}
public Node(int data){
this.data= data;
this.next = null;
}
public Node(int data, Node next){
this.data = data;
this.next = next;
}
}
//*************************************//
package com.ds.azim;
public class SingleLinkedList {
//Single Linked list has a head tail and has a length
public Node head;
public Node tail;
public int length;
//constructor
public SingleLinkedList(){
head = new Node();
length = 0;
}
public void insertAtFirst(int data){
head = new Node(data,head);
}
public void insertAtEnd(int data){
Node curr = head;
if(curr==null){
insertAtFirst(data);
}else{
while(curr.next!=null){
curr = curr.next;
}
curr.next = new Node(data,null);
}
}
public void show(){
Node curr = head;
while(curr.next!=null){
//do something
System.out.print(curr.data+",");
curr = curr.next;
}
}
public static void main(String[] args){
SingleLinkedList sll = new SingleLinkedList();
sll.insertAtFirst(12);
sll.insertAtFirst(123);
sll.insertAtFirst(890);
sll.insertAtEnd(234);
sll.show();
}
}
Along with removing this part of the code
public SingleLinkedList() {
head = new Node();
length = 0;
}
change your show function as well, because this will not print the last element
while(curr.next!=null){
//do something
System.out.print(curr.data+",");
curr = curr.next;
}
after this while, put one more print statement to print the last element.
System.out.print(curr.data);
this will fix the errors.
Your code initializes the list with a Node containing (0, null) and head pointing to it. To fix this, don't do that.
public SingleLinkedList() {
head = new Node();
length = 0;
}
Also in that code you set length = 0;, but actually the length is 1. Remove both the assignments from the constructor. Then you will have a structure with zero members and the length will be correct.
You have a tail variable which should point to the last node in your list. You should be keeping it up to date:
class SingleLinkedList {
private Node head = null;
private Node tail = null;
public void addAtHead(int data) {
if (head == null) {
addFirst(data);
} else {
head.next = new Node(data, head.next);
if (tail == head)
tail = head.next;
}
}
public void addAtTail(int data) {
if (head == null) {
addFirst(data);
} else {
assert tail != null;
assert tail.next == null;
tail.next = new Node(data);
tail = tail.next;
}
}
private void addFirst(int data) {
assert head == null;
assert tail == null;
head = new Node(data);
tail = head;
}
}
If you want to remove the tail variable, then:
class SingleLinkedList {
private Node head = null;
public void addAtHead(int data) {
if (head == null) {
head = new Node(data);
} else {
head.next = new Node(data, head.next);
}
}
public void addAtTail(int data) {
if (head == null) {
head = new Node(data);
} else {
Node curr = head;
while (curr.next != null)
curr = curr.next;
curr.next = new Node(data);
}
}
}

Linked list node pointing to nodes of different type

This is my first post here, but I'm not new to the site (call me a lurker).
Unfortunately this time I cannot seem to find an answer to my question without asking.
Anyway, to the point.
I am writing a small snakes and ladders (aka chutes and ladders) program in java for a data structures course. I had to write my own Linked List (LL) class, (I know that there is a java util that does it better, but I have to learn about the workings of the data structure) and that is not a problem. My LL is 'semi-Double linked' as I like to call it, since it links forward, but has another pointer field for other links, which is not necessarily used in every node.
What I want to know is if it is possible to link a node from a list to another list, which is of a different type.
Poor example:
(eg.) How would one link a node of type to a node of type ? Let us say we have a LL of 7 int values [1,2,3,4,5,6,7], and a LL of 7 Strings [Monday, Tuesday, Wednesday,Thursday, Friday, Saturday, Sunday]. We want to link the node containing 1 to the node containing Monday.
To be exact the problem I am having is as follows:
I have 100 nodes forward-linked, forming the game board, and a circularly linked list of 4 . I want to link the player nodes to their respective positions on the board, so that as they traverse the board, they can also follow the "snakes" and "ladders" links.
Thanks in advance!
My LLNode.java and LL.java are attached.
// LLNode.java
// node in a generic linked list class, with a link
public class LLNode<T>
{
public T info;
public LLNode<T> next, link;
public LLNode()
{
next = null;
link= null;
}
public LLNode(T element)
{
info = element;
next = null;
link = null;
}
public LLNode(T element, LLNode<T> n)
{
info = element;
next = n;
link = null;
}
public T getInfo()
{
return info;
}
public void setInfo(T element)
{
info = element;
}
public LLNode<T> getNext()
{
return next;
}
public void setNext(LLNode<T> newNext)
{
next = newNext;
}
public LLNode<T> getLink()
{
return link;
}
public void setLink(LLNode<T> newLink)
{
link = newLink;
}
}
// SLL.java
// a generic linked list class
public class LL<T>
{
private LLNode<T> head, tail;
public LLNode<T> current = head;
public LL()
{
head = tail = null;
}
public boolean isEmpty()
{
return head == tail;
}
public void setToNull()
{
head = tail = null;
}
public boolean isNull()
{
if(head == tail)
if(head == null || tail == null)
return true;
else
return false;
else
return false;
}
public void addToHead(T element)
{
head = new LLNode<T>(element, head);
if (tail == null)
tail = head;
}
public void addNodeToHead(LLNode<T> newNode)
{
head = newNode;
if (tail == null)
tail = head;
}
public void addToTail(T element)
{
if (!isNull())
{
tail.next= new LLNode<T>(element);
tail = tail.next;
}
else head = tail = new LLNode<T>(element);
}
public void addNodeToTail(LLNode<T> newNode)
{
if (!isNull())
{
tail.next= newNode;
tail = tail.next;
}
else head = tail = newNode;
}
public void addBefore(T element, T X)
{
if (!isEmpty()) // Case 1
{
LLNode<T> temp, n;
temp = head;
while( temp.next != null )
{
if( temp.next.info == X )
{
n = new LLNode<T>(element, temp.next);
temp.next = n;
return;
}
else
temp = temp.next;
}
}
else // Case 2
head = new LLNode<T>(element, head);
}
public void addBefore(T element, LLNode<T> X)
{
if (!isEmpty()) // Case 1
{
LLNode<T> temp, n;
temp = head;
while( temp.next != null )
{
if( temp.next == X )
{
n = new LLNode<T>(element, X);
temp.next = n;
return;
}
else
temp = temp.next;
}
}
else // Case 2
head = new LLNode<T>(element, head);
}
public T deleteFromHead()
{
if (isEmpty())
return null;
T element = head.info;
if (head == tail)
head = tail = null;
else head = head.next;
return element;
}
public T deleteFromTail()
{
if (isEmpty())
return null;
T element = tail.info;
if (head == tail)
head = tail = null;
else
{
LLNode<T> temp;
for (temp = head; temp.next != tail; temp = temp.next);
tail = temp;
tail.next = null;
}
return element;
}
public void delete(T element)
{
if (!isEmpty())
if (head == tail && (element.toString()).equals(head.info.toString()))
head = tail = null;
else if ((element.toString()).equals(head.info.toString()))
head = head.next;
else
{
LLNode<T> pred, temp;
for (pred = head, temp = head.next; temp != null && !((temp.info.toString()).equals(element.toString())); pred = pred.next, temp = temp.next);
if (temp != null)
pred.next = temp.next;
if (temp == tail)
tail = pred;
}
}
public void listAll()
{
if(isNull())
System.out.println("\tEmpty");
else
{
for ( LLNode<T> temp = head; temp!= tail.next; temp = temp.next)
System.out.println(temp.info);
}
}
public LLNode<T> isInList(T element)
{
LLNode<T> temp;
for ( temp = head; temp != null && !((temp.info.toString()).equals(element.toString())); temp = temp.next);
return temp ;
}
public LLNode<T> getHead()
{
return head;
}
public LLNode<T> getTail()
{
return tail;
}
public LLNode<T> getCurrent()
{
return current;
}
public void incrementCurrent()
{
current = current.next;
}
public void followCurrentLink()
{
current = current.link;
}
}
Any specific reason you want to generics for the specific problem domain of the node objects?
If you want to have this effect, another way to do it might be have an interface for node object (maybe call it ILinkNode), have the getInfo and setInfo overridden in two different node classes. Then the nodeLink can point to interface object without special type casting everywhere in the code.
Use in the first list, i.e. the one containing the node you want to link to the node in the other list, Object as the generic type instantiation.
Something like:
LL<Object> ll = new LL<Object>();
If you do this, you have to take care to cast to the specific type, each time you retrieve a node's value from the list.

Categories