In Java Create a doubly linked list whose nodes contain Stri

In Java

Create a doubly linked list whose nodes contain Strings. Your list should include the following methods: Insert a node in the list in alphabetical order Find a node that matches a String Traverse the list forwards and print Traverse the list backwards and print Delete a node from the list Delete/destroy the list In addition to creating the class(es) for your linked list, you\'ll need to create a main method that thoroughly tests each function you build to show that it works. You should do these things in

Solution

import java.util.NoSuchElementException;
import java.lang.*;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
String element;
Node next;
Node prev;

public Node(String element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }

public boolean isEmpty() { return size == 0; }

public int add(String element)
{
System.out.println(\"adding: \"+element);
Node tmp = new Node(element, head, null);
if(head == null)
{
tail = tmp;
head = tmp;
size++;
}
else
{
Node tmp1 = head;
while(tmp1.next != null)
{
String str = tmp1.element;
if(element.compareTo(str) < 0)
{
tmp.prev = tmp1.prev;
tmp.next = tmp1;
size++;
return 0;
}
tmp1 = tmp1.next;
}
tmp1.next = tmp;
}
}



public void iterateForward(){

System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}

public void iterateBackward(){

System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}

public String removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}

public String removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}

public static void main(String a[]){

DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.add(\"Hello\");
dll.add(\"Welcome\");
dll.add(\"Java\");
dll.iterateForward();
dll.iterateBackward();
dll.removeFirst();
dll.removeLast();
dll.iterateForward();
}
}

In Java Create a doubly linked list whose nodes contain Strings. Your list should include the following methods: Insert a node in the list in alphabetical order
In Java Create a doubly linked list whose nodes contain Strings. Your list should include the following methods: Insert a node in the list in alphabetical order

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site