Generic Doubly Linked List - java

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

Related

Make an int search(Object o) method for a stack that uses nodes

I'm trying to make a generic stack and queue class that uses the generic node class. It has empty(), pop(), peek(), push(), and a search() method. I know there is a built-in Stack class and stack search method but we have to make it by using the Node class.
I am unsure of how to make the search method. The search method is supposed to return the distance from the top of the stack of the occurrence that is nearest the top of the stack. The topmost item is considered to be at distance 1; the next item is at distance 2; etc.
My classes are below:
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
private Node<E> head;
private int nodeCount;
public static void main(String args[]) {
}
public E peek() {
return this.head.getData();
}
public E pop() {
E item;
item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head==null) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
// todo
}
}
public class Node<E>
{
E data;
Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
public class MyQueue<E> implements QueueInterface<E>
{
private Node<E> head;
private int nodeCount;
Node<E> rear;
public MyQueue()
{
this.head = this.rear = null;
}
public void add(E item){
Node<E> temp = new Node<E>(item);
if (this.rear == null) {
this.head = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public E peek(){
return this.head.getData();
}
public E remove(){
E element = head.getData();
Node<E> temp = this.head;
this.head = this.head.getNext();
nodeCount--;
return element;
}
}
After working on it based off of the first comment I have this:
public int search(Object o){
int count=0;
Node<E> current = new Node<E> (head.getData());
while(current.getData() != o){
current.getNext();
count++;
}
return count;
}
It doesn't have any errors but I cannot tell if it is actually working correctly. Does this seem correct?
It needs the following improvements,
search method should have parameter of type 'E'. So, the signature should look like public int search(E element)
start the count with 1 instead of 0.As you have mentioned topmost item is considered to be at distance 1
initialize current with head, because creating a new node with data value of head(new node(head.getData())) will create an independent node with data same as head node; and the while will run only for the head node as current.getNext() will be null always. Node<E> current = head will create another reference variable pointing to the head.
Instead of != in condition, use if( !current.getData().equals(element.getData())) )
If using your own class as data type, don't forget to override equals method.
Change current.getNext(); to current = current.getNext();
You have problems with other method. Pay attention on top == null. To calculate search() all you need is just iterate over the elements and find position of required value:
public class MyStack<E> {
private Node<E> top;
private int size;
public void push(E val) {
Node<E> node = new Node<>(val);
node.next = top;
top = node;
size++;
}
public E element() {
return top == null ? null : top.val;
}
public E pop() {
if (top == null)
return null;
E val = top.val;
top = top.next;
size--;
return val;
}
public boolean empty() {
return size == 0;
}
public int search(E val) {
int res = 1;
Node<E> node = top;
while (node != null && node.val != val) {
node = node.next;
res++;
}
return node == null ? -1 : res;
}
private static final class Node<E> {
private final E val;
private Node<E> next;
public Node(E val) {
this.val = val;
}
}
}
I assume your MyStack class should be compatible with the Stack class provided by Java as you mention it in your question. This means that your signature public int search(Object o) matches the signature of java.util.Stack#search (apart from synchronised).
To implement the search method using your Node class, we need to traverse the stack and return the index of the first (uppermost) match. First, assign head to a local variable (current). Then you can create a loop where you current.getNext() at the end to get the next element. Stop if the next element is null as we have reached the end of the stack. In the loop, you either count up the index or return this index when the current element's data matches the argument o.
The evaluation needs to be able to deal with null values for your argument o. Therefore, you need to check for null first and adjust your logic accordingly. When o is null, do a null-check against current.getData(). If o is not null, check if current.getData() is equal to o with equals().
Here is a working example: (compatible with java.util.Stack#search)
public int search(Object o) {
int index = 1;
Node<E> current = head;
while (current != null) {
if (o == null) {
if (current.getData() == null) {
return index;
}
} else {
if (o.equals(current.getData())) {
return index;
}
}
current = current.getNext();
index++;
}
return -1; // nothing found
}
To test this, you can write a simple unit test with JUnit like this:
#Test
public void testMyStackSearch() {
// initialize
final MyStack<String> stack = new MyStack<>();
stack.push("e5");
stack.push("e4");
stack.push(null);
stack.push("e2");
stack.push("e1");
// test (explicitly creating a new String instance)
assertEquals(5, stack.search(new String("e5")));
assertEquals(3, stack.search(null));
assertEquals(2, stack.search(new String("e2")));
assertEquals(1, stack.search(new String("e1")));
assertEquals(-1, stack.search("X"));
}
Since you have already a reference implementation, you can replace MyStack with Stack (java.util.Stack) and see if your asserts are correct. If this runs successfully, change it back to MyStack and see if your implementation is correct.
Note: I do not recommend to actually use the Stack implementation in Java. Here, it just serves as a reference implementation for the java.util.Stack#search method. The Deque interface and its implementations offer a more complete and consistent set of LIFO stack operations, which should be used in preference to Stack.

Java Linked List add Method

I am attempting to implement a linked list that uses a node class containing head, tail, and current nodes. Part of the linked list is an add method that should add a value to the end of the current node in the list just like an actual linked list would. My issue is that it only works for the first node and then just stops there. For example, in my main I tried testing the code by calling add(1); and add(2);. The console shows me 1 but that's all. I'm unsure if the error is in my add method, toString method, or node class.
I'll also add that I tested whether the correct values were being assigned to "current" in either case, and they were. This has led me to wonder if it's the toString that is the root of the issues, however no matter how much I try I can't change it to make any improvements.
I've hoping fresh eyes may be able to find any blaring issues that may exist.
Add method:
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
Node class:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
toString:
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
All:
public class IntLList extends IntList{
public IntLList(){
}
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
Node head = null;
Node tail = null;
Node current = null;
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
public int get(int index){
return 0;
}
public void set(int index, int val){
}
public void remove(int index) throws ArrayIndexOutOfBoundsException{
}
public int size(){
return 0;
}
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
return "temp";
}
public void removeLast(){
}
public boolean isEmpty(){
boolean isEmpty = false;
if(head == null){
isEmpty = true;
}
return isEmpty;
}
public void clear(){
}
public static void main(String[] args) {
IntLList i = new IntLList();
i.add(1);
i.add(2);
i.toString();
}
}
Make the following changes:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = NULL; // this is to set the next node of current node to null
if(next!=NULL)
next.next=this; // this is to set the previous node to point to current node
}
}

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
}

How do I write basic Doubly Linked List functions in Java?

My first assignment in my programming class is about writing code for a Doubly Linked List, which includes writing an add, remove, size, iterator first, iterator last, and iterator find functions. I have spent 3 hours and gotten no where in understanding this. I understand what happens if I can see it in a picture. But my problem is translating it to code. This is what I have so far:
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data, node next, node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null, null, null);
footer = new node(null, header, null);
header.next = footer;
}
public void add(G data) {
header.next = new node(data, footer.prev, footer);
}
public int size() {
node current = header.next;
int quanity = 0;
if (current == null) {
return 0;
}
while (current != null) {
current = current.next;
quanity++;
}
return quanity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
As you can see, I've been using the main() to test everything. From what I've been told by my teacher, my constructor and node class look fine. However I know either my add and size are not right because when I test this, when there is no nodes in the list, it displays nothing, but it should display 0 right? I mean, assuming my size code is right, which I'm not sure of.
And whenever I add a node, no matter how many I add, it always displays 1. So either both add and size are broken, or both are. I have not written the other functions as it makes no sense until I figure these ones out. Please someone help me understand this! Thank you.
Declare a size field in DoublyLinkedList to store the current size of the list. When add succeed, make size++. When remove succeed, make size--. And size() method just simply return the value of size.
The sample code is here:
private int size = 0;
public void add(G data) {
header.next = new node(data, footer.prev, footer);
size++;
}
public int size() {
return size;
}
Noticed couple of things:
First, footer is not constructed correctly. It should be:
public DoublyLinkedList() {
..
footer = new node(null, null, header);
// your code is incorrectly creating a circular list
..
}
Secondly add() method doesn't look correct. It should be something like :
public void add(G data) {
Node newNode = new Node(data, header, null);
header.prev = newNode
header = newNode;
}
// for adding at the front (LIFO)
OR
public void add(G data) {
Node newNode = new Node(data, null, footer);
footer.next = newNode
footer = newNode;
}
//for adding at the tail (FIFO)
Check out the wikipedia entry for doubly linked lists. It has some good pseudo code.
Using your own code I'm going to make a few suggestions
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null);
footer = new node(null);
header.next = footer;//link the header to the footer
footer.prev = header;//link the footer to the header
}
public void add(G data) { //assuming you are adding the node to the head of the list
node newNode = new node(data); //creating new node to add with the data
newNode.next = header.next; // setting new node to head of the list or the footer
newNode.prev = header; //setting the new node's previous node to the header
header.next = newNode; //setting the newNode as the next node.
}
public int size() {
node current = header.next;
int quantity = 0;
if (current.data == null/*Empty list*/) { //you needed to specify what you were trying to test
return 0;
}
while (current.data != null/*traversing the list*/) {
current = current.next;
quantity++;
}
return quantity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
Here you go:
public class DoublyLinkedList {
private class Node {
String value;
Node next,prev;
public Node(String val, Node n, Node p) {
value = val;
next = n;
prev=p;
}
Node(String val) {
this(val, null, null);
}
}
private Node first;
private Node last;
public DoublyLinkedList() {
first = null;
last = null;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
int count=0;
Node p=first;
while(p!=null){
count++;
p=p.next;
}
return count;
}
public void add(String e) {
if(isEmpty()){
last=new Node(e);
first=last;
}
else{
last.next=new Node(e, null, last);
last=last.next;
}
}
public void add(int index, String e){
if(index<0||index>size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if(index==0){
Node p=first;
first=new Node(e,p,null);
if(p!=null)
p.prev=first;
if(last==null)
last=first;
return;
}
Node pred=first;
for(int k=1; k<=index-1;k++){
pred=pred.next;
}
Node succ=pred.next;
Node middle=new Node(e,succ,pred);
pred.next=middle;
if(succ==null)
last=middle;
else
succ.prev=middle;
}
public String toString(){
StringBuilder strBuilder=new StringBuilder();
Node p=first;
while(p!=null){
strBuilder.append(p.value+"\n");
p=p.next;
}
return strBuilder.toString();
}
public String remove(int index){
if(index<0||index>=size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
Node target=first;
for(int k=1; k<=index;k++){
target=target.next;
}
String element=target.value;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return element;
}
public boolean remove(String element){
if(isEmpty())
return false;
Node target=first;
while(target!=null&&!element.equals(target.value))
target=target.next;
if(target==null)
return false;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return true;
}
public static void main(String[] args){
DoublyLinkedList list1=new DoublyLinkedList();
String[] array={"a","c","e","f"};
for(int i=0; i<array.length; i++){
list1.add(array[i]);
}
list1.add(1,"b");
list1.add(3,"d");
System.out.println(list1);
}
}

Categories