Insert new element in Double Linked List - java

I have to implement double linked lists. The method prepend should insert a new element bevor the existing list. But I dont know how to link the reference "next" of the new element with the reference "prev" of the old list.
Thanks in advance.
public class DoublyLinkedList {
private String info;
private DoublyLinkedList next;
private DoublyLinkedList prev;
public DoublyLinkedList(String info) {
this.info = info;
this.next = this.prev = null;
}
private DoublyLinkedList(String info, DoublyLinkedList prev, DoublyLinkedList next) {
this.info = info;
this.prev = prev;
this.next = next;
}
DoublyLinkedList prepend(String info) {
// Beginning of a list, insert new element
if (prev == null) {
prev = new DoublyLinkedList(info, null, next);
} else {
prev.prepend(info);
}
return prev;
}

Start by naming your class DoublyLinkedNode. A linked series of such objects would make a doubly linked list.
It's really important for your thinking to use the right class names. Once you fix your nsme ie node not list, the problem should becone a lot easier.
In pseudo code:
set previous of root to new node
set new node next to root
set root to new node

You need to link the new node with the current node by setting the next_link of the new node with the current node.
public class DoublyLinkedList {
...
DoublyLinkedList prepend(String info) {
// Beginning of a list, insert new element
if (prev == null) {
// this is the changed line.
prev = new DoublyLinkedList(info, null, this);
} else {
prev.prepend(info);
}
return prev;
}
}

Related

Java class with generic data types

I am trying to write a simple linked list class that uses generic data type. I am new to Java so I can't figure out how to debug the error message in the main method that arises when I try to insert data into an instance of my class. The class code and the main method are as follows:
import java.io.*;
// Java program to implement
// a Singly Linked List
public class MyLinkedList<T> {
Node head; // head of the list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d)
{
data = d;
next = null;
}
}
// Method to insert a new node
MyLinkedList insert(MyLinkedList list, T data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
// Return the list by head
return list;
}
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
MyLinkedList list = new MyLinkedList();
// Insert the values
list = insert(list, 1);
}
}
You need to change int to T in class declaration and method signature.
class MyLinkedList<T> {
MyLinkedList() {
head=null;
}
Node head; // head of list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d) {
data = d;
next = null;
}
}
// Method to insert a new node
public void insert(T data) {
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (this.head == null) {
this.head = new_node;
} else {
Node last = this.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
}
protected void display() {
Node myNode=head;
System.out.println();
while (myNode != null) {
System.out.println(myNode.data);
myNode=myNode.next;
}
}
Change the insert method signature to the below:
public static void main(String[] args) {
/* Start with the empty list. */
MyLinkedList<Integer> list = new MyLinkedList<Integer>();
// Insert the values
list.insert(1);
list.insert(3);
list.insert(12);
list.insert(11);
list.insert(21);
list.insert(22);
list.insert(45);
list.display();
}
For clear coding and understanding I have changed class name as MyLinkedList

Need guidance on creating Node class (java)?

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

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
}

Generic Doubly Linked List

For my personal practice I am trying to make a basic, generic doubly linked list and I want to know if the methods addtoHead() and addtoTail() I made are correct and efficient and if not what would be better? and how could I remove from the list for the methods removingDataAt(), removingFromTail(), removingFromHead()?
Node class:
public class PracticeNode<T> {
private T data;
private PracticeNode<T> next;
private PracticeNode<T> prev;
PracticeNode() {
next = null;
prev = null;
data = null;
}
PratciceNode(T data) {
this(data, null, null);
}
PracticeNode(T data, PracticeNode<T> next, PracticeNode<T> prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
public void setNextNode(PracticeNode<T> next) {
this.next = next;
}
public void setPrevNode(PracticeNode<T> prev) {
this.prev = prev;
}
public void setData(T data) {
this.data = data;
}
public PracticeNode<T> getNextNode() {
return next;
}
public PracticeNode<T> getPrevNode() {
return prev;
}
public T getData() {
return data;
}
}
Linked list class:
public class PracticeLinkedList<T> {
private PracticeNode<T> head;
private PracticeNode<T> tail;
public void addtoHead(T data ) {
PracticeNode<T> newnode=new PracticeNode<T>();
if(head==null){
head=newnode;
tail=newnode;
newnode.setNextNode(null);
newnode.setPrevNode(null);
}else{
newnode.setNextNode(head);
head.setPrevNode(newnode);
head=newnode;
}
}
public void addToTail(T data) {
PracticeNode<T> newnode=new PracticeNode<T>();
if(tail==null){
head=newnode;
tail=newnode;
newnode.setNextNode(null);
newnode.setPrevNode(null);
}else{
newnode.setPrevNode(tail);
tail.setNextNode(newnode);
tail=newnode;
}
}
public T removingDataAt (int){
//....
}
public T removingFromTail (){
//....
}
public T removingFromHead (){
//....
}
}
addToTail looks good to me.
With removingDataAt(), removingFromTail(), and removingFromHead(), you want to do what you have done with addToTail and addToHead. Because this seems like it is something from an assignment, I will not give the completed code, but just tell you how to do it.
I see that you have only the navigating instances of head and tail, I would recommend that you also implement a 'current' which will allow you to navigate through the List to do things such as removingDataAt(location). I'm not sure about the most efficient method of removing things, but with Java, it does garbage collection automatically so you could simply remove from the head by using head = head.getNextNode(). Removing from tail is a similar story.
For removingDataAt() you will need a method to find the data data first, unless the use already knows what is in each location of the list. Perhaps something like find(object) which will return an error message on fail and move the 'current' instance to the found object otherwise. You'd implement it by using something like this:
for(current = head; current!=null; current = current.getNextNode())
Remember to check if there are any other items in the linked list.
Here is a solid implementation of doubly linked list:
http://algs4.cs.princeton.edu/13stacks/DoublyLinkedList.java.html
Add method looks like this:
// add element to list
public void add(Item item) {
Node x = current.prev;
Node y = new Node();
Node z = current;
y.item = item;
x.next = y;
y.next = z;
z.prev = y;
y.prev = x;
N++;
index++;
lastAccessed = null;
}
What to note here:
a> <b> <c> <e> <f> <g
if you want to add d, then find e and add d
public void add(Item item) {
Node x = current.prev; //new before element : c
Node y = new Node(); //new node to store element
Node z = current; //new after element : e
y.item = item; //store value to the node : d.value=value
x.next = y; //link before element next : c>
y.next = z; //link element next : d>
z.prev = y; //link after element previous : <e
y.prev = x; //link after element previous : <d
N++; //increase number of elements on list counter
index++; //increase current position number
lastAccessed = null;
}
now you should have :
a> <b> <c> <d> <e> <f> <g

How to implement getPrevious() method for double linked list?

We were given the following code from the last assignment to use for singly linked list, but we're supposed to add in a getPrevious() and setPrevious() method. The following code works for the singly linked list as I completed the assignment and got 100%.
I searched online and read my book but couldn't find a solution.
For a singly linked list I would start from the head and iterate until the getNext() == current or something of the like. Obviously that beats the purpose of a doubly linked list, so any ideas?
public class Node
{
private Object item;
private Node next;
public Node()
{
this.next = null;
}
public Node(Object newItem)
{
this.item = newItem;
this.next = null;
}
public Node(Object newItem, Node newNext)
{
this.item = newItem;
this.next = newNext;
}
public Object getItem()
{
return this.item;
}
public void setItem(Object newItem)
{
this.item = newItem;
}
public Node getNext()
{
return this.next;
}
public void setNext(Node newNext)
{
this.next = newNext;
}
}
You just need to to add an extra member similar to next that would point to the previous node in the list. Having done that, adding a getter and a setter would be trivial.
(You will, of course, need to change your implementation of the linked list to correctly populate this new member.)
So... where's the problem?
Node previous;
public Node getPrevious() {
return previous;
}
public void setPrevious(Node node) {
this.previous = node;
}
If you are to make the list a doubly-linked-list you have to implement the "other", opposite-direction link. You do it by adding nother field for each node. And you also have to update the field each time you modify the list.

Categories