Sorting a generic LinkedList - java

I have to sort through a LinkedList, but i can't figure out why it only sorts it once and then stops. I am having a hard time understanding generic types and how to use them. Most of the examples i found were about sorting integer arrays, but i still couldn't translate those examples into my sort method. Anything that could help me understand how to sort this would be greatly appreciated.
public void sort() {
Node<T> current = head;
while(current != null){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
Here is my LinkedList class
public class LinkedList<T extends Comparable<T>> implements LinkedList161<T> {
protected Node<T> head;
protected int size;
public LinkedList() {
head = null;
size = 0;
}
public void add(T item, int index) {
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("out of bounds");
}
if(index == 0){
head = new Node<T>(item, head);
}
else{
Node<T> current = head;
for(int i = 0; i < index -1; i ++){
current = current.getNext();
}
current.setNext(new Node<T>(item, current.getNext()));
}
size++;
}
public void addFirst(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToFront(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToBack(T item) {
if(head == null){
head = new Node<T>(item);
size++;
}
else{
Node<T> temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
temp.setNext(new Node<T>(item));
size++;
}
}
public void remove(int index) {
if(index < 0 || index > size){
System.out.println("Index out of bounds");
}
if(index == 0){
head = head.getNext();
}else{
Node<T> current = head;
for(int i = 0; i < index;i++){
current = current.getNext();
}
current.setNext(current.getNext().getNext());
}
size--;
}
public T get(int index){
Node<T> p = head;
for(int i = 0; i < index;i++){
p = p.getNext();
}
return p.getItem();
}
public void clear() {
head = null;
size = 0;
}
public int size() {
return size;
}
#Override
public String toString() {
String result = "";
if (head == null)
return result;
for (Node<T> p = head; p != null; p = p.getNext()) {
result += p.getItem() + "\n";
}
return result.substring(0,result.length()-1); // remove last \n
}
#Override
public void sort() {
Node<T> current = head;
for(int i = 0; i < size;i++){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
}
Here is my Node class
public class Node<T> implements Node161<T>{
protected T item;
protected Node<T> next;
public Node(T item, Node<T> next) {
setItem(item);
setNext(next);
}
public Node(T item) {
setItem(item);
}
public T getItem() {
return item;
}
public void setItem(T i) {
item = i;
}
public void setNext(Node<T> n) {
next = n;
}
public Node<T> getNext() {
return next;
}
#Override
public String toString() {
return item.toString();
}
}

Your implementation of sort does just one step of sorting: it orders adjacent items and after this step things get better but the whole collection will not be sorted. You should repeat this step until your collection gets sorted.
Note that this algorithm is not efficient. You should look at some more sophisticated approach like merge sort

Wiki merge sort article now includes a simple but fast bottom up merge sort for linked lists that uses a small array (usually 26 to 32) of pointers to the first nodes of a list, where array[i] is either null or points to a list of size 2 to the power i. Unlike some other approaches, there's no scanning of lists, instead, the array is used along with a common merge function that merges two already sorted lists. Link to article:
http://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists

Related

Generic linked-list remove, size, get methods

I have just seen this wonderful code from this question "Generic Linked List in java" here on Stackoverflow. I was wandering on how do you implement a method remove (to remove a single node from the linkedlist), size (to get the size of list) and get (to get the a node). Could someone please show me how to do it?
public class LinkedList<E> {
private Node head = null;
private class Node {
E value;
Node next;
// Node constructor links the node as a new head
Node(E value) {
this.value = value;
this.next = head;//Getting error here
head = this;//Getting error here
}
}
public void add(E e) {
new Node(e);
}
public void dump() {
for (Node n = head; n != null; n = n.next)
System.out.print(n.value + " ");
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("world");
list.add("Hello");
list.dump();
}
}
Your implementation of LinkedList for operation remove(), size() and contains()
looks like this:
static class LinkedList<Value extends Comparable> {
private Node head = null;
private int size;
private class Node {
Value val;
Node next;
Node(Value val) {
this.val = val;
}
}
public void add(Value val) {
Node oldHead = head;
head = new Node(val);
head.next = oldHead;
size++;
}
public void dump() {
for (Node n = head; n != null; n = n.next)
System.out.print(n.val + " ");
System.out.println();
}
public int size() {
return size;
}
public boolean contains(Value val) {
for (Node n = head; n != null; n = n.next)
if (n.val.compareTo(val) == 0)
return true;
return false;
}
public void remove(Value val) {
if (head == null) return;
if (head.val.compareTo(val) == 0) {
head = head.next;
size--;
return;
}
Node current = head;
Node prev = head;
while (current != null) {
if (current.val.compareTo(val) == 0) {
prev.next = current.next;
size--;
break;
}
prev = current;
current = current.next;
}
}
}

DoublyLinkedList Issues traveling backwards

I have an assignment to complete a DoublyLinkList assignment and I am having some difficulty with two of the methods. I was given the code for MyList and MyAbstractList and was told to extend MyAbstractList with my DoublyLinkedList. I am not allowed to change MyList or MyAbstractList.
Here is the code for MyList I was provided:
public interface MyList<E extends Comparable<E>> {
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the number of elements in this list */
public int size();
/** Add a new element at the proper point */
public void add(E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the first element in the list */
public E getFirst();
/** Return the last element in the list */
public E getLast();
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public boolean remove(int index);
/** Remove the first element in the list, return true if done, false if list is empty */
public boolean removeFirst();
/** Remove the Last element in the list, return true if done, false if list is empty */
public boolean removeLast();
/** Replace the element at the specified position in this list
* with the specified element and return true if done, false if index out of range. */
public boolean set(int index, E e);
}
and this was the code I was provided for MyAbstractList:
public abstract class MyAbstractList<E extends Comparable<E>> implements MyList<E> {
protected int size = 0; // The size of the list
/** Create a default list */
protected MyAbstractList() {
}
/** Create a list from an array of objects */
public MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
#Override /** Return true if this list contains no elements */
public boolean isEmpty() {
return size == 0;
}
#Override /** Return the number of elements in this list */
public int size() {
return size;
}
}
Finally here is my code for MyDoublyLinkedList:
import java.util.ArrayList;
public class MyDoublyLinkedList<E extends Comparable<E>> extends MyAbstractList<E>
{
int size =0;
Node<E> head = null;
Node<E> current = null;
Node<E> tail = null;
public MyDoublyLinkedList() {
}
/** Create a list from an array of objects */
public MyDoublyLinkedList(E[] objects) {
super(objects);
}
#Override
public boolean isEmpty()
{
return size == 0;
}
#Override
public int size()
{
return size;
}
/** Add a new element at the proper point */
#Override
public void add(E e)
{
Node<E> newNode = new Node<E>(e);
if (tail == null) {
head = tail = newNode;
}
else //if (head != null)
{
tail.next = newNode;
tail = newNode;
}
size++;
}
#Override
public void clear()
{
size = 0;
head = tail = null;
}
#Override
public boolean contains(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return true;
current = current.next;
}
return false;
}
#Override
public E get(int index)
{
if (index < 0 || index > size - 1)
return null;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
return current.element;
}
#Override
public E getFirst()
{
if (size == 0) {
return null;
}
else {
return head.element;
}
}
#Override
public E getLast()
{
if (size == 0) {
return null;
}
else {
return tail.element;
}
}
#Override
public int indexOf(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return i;
current = current.next;
}
return -1;
}
#Override
public int lastIndexOf(E e)
{
int lastIndex = -1;
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
lastIndex = i;
current = current.next;
}
return lastIndex;
}
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
#Override
public boolean remove(E e)
{
int index = indexOf(e);
if (index != -1) {
return remove(index);
} else {
return false;
}
}
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
#Override
public boolean remove(int index)
{
if (index < 0 || index >= size) {
return false;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return true;
}
}
#Override
public boolean removeFirst()
{
if (size == 0) {
return false;
}
else {
Node<E> temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return true;
}
}
#Override
public boolean removeLast()
{
if (size == 0) {
return false;
}
else if (size == 1) {
Node<E> temp = head;
head = tail = null;
size = 0;
return true;
}
else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
Node<E> temp = tail;
tail = current;
tail.next = null;
size--;
return true;
}
}
#Override
public boolean set(int index, E e)
{
if (index < 0 || index > size - 1)
return false;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
E temp = current.element;
current.element = e;
return true;
}
#Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.next;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public String toStringBack()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = tail;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.previous;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public void add(int index, E e)
{
if (index ==0) {
addFirst(e);// The new node is the only node in list
}
else if(index > size)
{
addLast(e);//The index location was bigger than size
}
else
{
Node<E> current = getAtIndex(index-1);
Node<E> temp = current.next;
current.next = new Node<E>(e);
(current.next).next = temp;
size++;
}
}
public void addFirst(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
public void addLast(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++;
}
protected Node<E> getAtIndex(int index)
{
int count;
if (index < 0 || index > size - 1)
return null;
Node<E> temp = null;
if(index <= (size/2))
{
count = -1;
temp = head;
while(++count <= index){
temp = temp.next;
}
}
else if (index > (size/2))
{
count = size;
temp = tail;
while(--count >= index){
temp = temp.previous; //--> this is Where the null pointer exception occurs
}
}
return temp;
}
private static class Node<E>{
E element;
Node<E> next;
Node<E> previous;
public Node(E element){
this.element = element;
next = null;
previous = null;
}
}
}
When I run the add(int index, E e) Method I receive a null pointer exception in the getAtIndext() method. I also have had issues getting the add(E e) Method to add properly when I change the current location. The methods are all as I am being required to use them. The use of iterators while they would be nice are not allowed. I am using Bluj as a compiler. Please let me know what questions you have.
Thank you
EDIT: I do know what a Null Pointer Exception is, I can not figure out why this is coming back as null. The Node "current" should point to the end, then go back in the list until it reaches the indexed location. This only happens when I try to add a node in the last half of the list. The error is thrown at temp = temp.previous;
The stack trace is:
java.lang.NullPointerException at MyDoublyLinkedList.getAtIndex(MyDoublyLinkedList.java:345) at MyDoublyLinkedList.add(MyDoublyLinkedList.java:289) at TestMyDoublyLinkedList.main(TestMyDoublyLinkedList.java:50)
Edit: I figured out the issue. The add() and getAtIndex functions are running properly. When I run the test the function that is throwing a Null Pointer Exception is throwing it at position 8. It cycles through the first few nodes fine, but dies at node 8
When inserting in the add() method, you never assign previous so it is null for all nodes.

Deleting a node at a given index in Java; What am I doing wrong?

I have been stuck for the last 40-so minutes on this problem. I'm unsure of what I am doing wrong here, I have tried debugging many times and have read similar Q/A's. Can't figure it out and my assignment is due at midnight.
It is not deleting the Node.. None at all in fact. If the code seems right, then the problem may be lying inside main. Let me know, please & thank you!
Any help is well appreciated! :)
Problem Method Below
void deleteAtIndex(int idx)
{
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
Full Class Code Below
public class ShapeLinkedList {
public Node head; // Head is first node in linked list
public ShapeLinkedList() { }
public ShapeLinkedList(Node head) {
}
public boolean isEmpty() {
return length() == 0;
}
public void insertAtEnd(Shape data) {
Node end = new Node(data, null);
if (head == null)
head.setNext(end);
else
tail().setNext(end);
}
public void insertAtBeginning(Shape data) {
if (data != null)
{
Node temp = new Node(data, head);
head = temp;
}
}
public Node tail() {
if (head == null){
return null;
}
else
{
Node temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
return temp;
}
}
public int length() { // 1
Node temp = head;
if (temp == null)
return 0;
int tempIndex = 0;
while(temp.getNext() != null){
temp = temp.getNext();
tempIndex++;
}
return tempIndex;
}
void insertAtIndex(int idx, Shape data) { //3
if (length() >= idx)
{
Node current = new Node(data, null);
Node temp = findAtIndex(idx);
current.setNext(temp.getNext());
temp.setNext(current);
}
}
Node findAtIndex(int idx) { // 2
if (length() >= idx)
{
Node temp = head;
for(int i = 0; i < idx; i++)
{
temp = temp.getNext();
}
return temp;
}
else
return null;
}
void deleteAtIndex(int idx) { //4
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
#Override
public String toString() {
return "";
}
void deleteData(Shape s) {
Node temp = head;
for(int i = 0; i < length(); i++)
{
if(temp.getData() == s)
deleteAtIndex(i);
}
}
#Override
public int hashCode() {
return 0;
}
#Override
public boolean equals(Object obj) {
return false;
}
// Node is nested class because it only exists along with linked list
public static class Node {
private Shape data;
private Node next;
public Node(Shape S, Node N){
data = S;
next = N;
}
public Node getNext(){
return next;
}
public Shape getData() { return data; }
public void setNext(Node N) { next = N; }
// TODO develop all the methods that are needed
// such as constructors, setters, getters
// toString, equals, hashCode
}
}
You have multiple bugs in your class. I guess if you fix them, your code will work fine. SO is not a debugging platform, thus your question is off-topic and you should learn using a debugger.
Here some issues I instantly have seen from a quick look at your code, I'm sure there are more issues:
if (length() >= idx) should probably be if (length() > idx) at all places and
if (head == null) head.setNext(end); should probably be if (head == null) head = end; and
public ShapeLinkedList(Node head) { } should probably be public ShapeLinkedList(Node head) { this.head = head; } and
int tempIndex = 0 should probably be int tempIndex = 1

Implementing Singly Linked List

I am trying to learn data structure, but I ran into the dreaded NullPointerException and I am not sure how to fix it.
My SinglyLinkedList<E> class implements an interface, LinkedList, where I redefined some methods like, add(), get(), contains(), and more.
The NullPointerException happens when I use the clear() method. It points at the method removeLast() under nodeBefore.setNext(null). It also points to the clear() method under remove(head.getElement()).
Also, if there is anything I can improve upon in my code please let me know.
public class SinglyLinkedList<E> implements LinkedList<E> {
private class Node<E> {
public Node<E> next;
public E element;
public Node(E element) {
this.element = element;
}
public Node (E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setElement(E element) {
this.element = element;
}
public void setNext(Node<E> next) {
this.next = next;
}
public String toString() {
return ("[" + element + "] ");
}
}
public Node<E> head;
public Node<E> tail;
public int total;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
this.total = 0;
}
public E get(int index) {
if (index < 0 || index > size()) {
return null;
}
if (index == 0) {
return head.getElement();
}
Node<E> singly = head.getNext();
for (int i = 1; i < index; i ++) {
if (singly.getNext() == null) {
return null;
}
singly = singly.getNext();
}
System.out.println("\n" + singly.getElement());
return singly.getElement();
}
public void add(E element) {
Node<E> singlyAdd = new Node<E>(element);
if (tail == null) {
head = singlyAdd;
tail = singlyAdd;
} else {
tail.setNext(singlyAdd);
tail = singlyAdd;
}
total++;
}
public void display() {
if (head == null) {
System.out.println("empty list");
} else {
Node<E> current = head;
while (current != null) {
System.out.print(current.toString());
current = current.getNext();
}
}
}
public boolean contains(E data) {
if (head == null) {
return false;
}
if (head.getElement() == data) {
System.out.println(head);
return true;
}
while (head.getNext() != null) {
head = head.getNext();
if (head.getElement() == data) {
System.out.println(head);
return true;
}
}
return false;
}
private Node<E> removeFirst() {
if (head == null) {
System.out.println("We cant delete an empty list");
}
Node<E> singly = head;
head = head.getNext();
singly.setNext(null);
total--;
return singly;
}
private Node<E> removeLast() {
Node<E> nodeBefore;
Node<E> nodeToRemove;
if (size() == 0) {
System.out.println("Empty list");
}
nodeBefore = head;
for (int i = 0; i < size() - 2; i++) {
nodeBefore = nodeBefore.getNext();
}
nodeToRemove = tail;
nodeBefore.setNext(null);
tail = nodeBefore;
total--;
return nodeToRemove;
}
public E remove(int index) {
E hold = get(index);
if (index < 0 || index >= size()) {
return null;
} else if (index == 0) {
removeFirst();
return hold;
} else {
Node<E> current = head;
for (int i = 1; i < index; i++) {
current = current.getNext();
}
current.setNext(current.getNext().getNext());
total--;
return hold;
}
}
public int size() {
return getTotal();
}
public boolean remove(E data) {
Node<E> nodeBefore, currentNode;
if (size() == 0) {
System.out.println("Empty list");
}
currentNode = head;
if (currentNode.getElement() == data) {
removeFirst();
}
currentNode = tail;
if (currentNode.getElement() == data) {
removeLast();
}
if (size() - 2 > 0) {
nodeBefore = head;
currentNode = head.getNext();
for (int i = 0; i < size() - 2; i++) {
if (currentNode.getElement() == data) {
nodeBefore.setNext(currentNode.getNext());
total--;
break;
}
nodeBefore = currentNode;
currentNode = currentNode.getNext();
}
}
return true;
}
public void clear() {
while (head.getNext() != null) {
remove(head.getElement());
}
remove(head.getElement());
}
private int getTotal() {
return total;
}
}
For your clear method, I don't see that you do any per element cleanup, and the return type is void, so all you want is an empty list. The easiest way is to simply clear everything, like in the constructor:
public void clear() {
this.head = null;
this.tail = null;
this.total = 0;
}
Another comment:
in contains, you do
while (head.getNext() != null) {
head = head.getNext();
if (head.getElement() == data) {
System.out.println(head);
return true;
}
}
which may have two problems (where the first applies to the entire class),
you compare with == data which compares references, where you probably want to compare values with .equals(data)
Edit: I.e. n.getElement().equals(data) instead of n.getElement() == data.
(Or, if n and data may be null, something like (data != null ? data.equals(n.getElement()) : data == n.getElement())
you use the attribute head as the scan variable which modifies the state of the list. Do you really want that?
The problem arises when you delete the last element within clear: remove(head.getElement());. For some reason, you first remove the head and then the tail. But when calling removeLast, you use the head (which is already null). Within removeLast this is the line, which causes the NullPointerException: nodeBefore.setNext(null);.
My advice would be to write the clear() method as #bali182 has suggested:
public void clear() {
this.head = null;
this.tail = head;
this.total = 0;
}
One advice: if you are writing methods to search or delete entries, you should never use == when dealing with objects (or even better: don't use == at all when dealing with objects). You may want to read this thread.
From within clear method, you are calling remove(head.getElement()); meaning you are trying to call LinkedList's remove method. And since you are overriding each functionality and so is add, you don't maintain internal state of LinkedList and hence you get exception. Code in remove is:
public boolean remove(Object o) {
if (o==null) {
for (Entry<E> e = header.next; e != header; e = e.next) {
if (e.element==null) {
So here since you are not using functionality of LinkedList, header would be null and doing header.next would return NullPointerException.

Inserting element in a doubly linked list

I'm trying to implement an insertAfterNth method that inserts an element after the nth(starting from 1, not 0) element on a doubly linked list. And, I'm stuck in setting the previous node to the node that I'm trying to insert. I need some help on figuring out the problem. Thanks.
public class DListNode {
public DListNode next;
public DListNode prev;
public int item;
...
}
public void insertAfterNth(int n, int item) {
if (n > length() || n < 1) {
System.out.println("error: out of bounds");
return;
}
else if (n == length()) {
insertEnd(item);
}
DListNode walker = head;
int i = 1;
while (i != n) {
i++;
walker = walker.next;
}
DListNode node = new DListNode(item);
node.next = walker.next;
walker.next.prev = node; /* not sure if this line of code is right, regardless this method is giving me errors(I'm most certain that this line is causing the problem)*/
walker.next = node;
node.prev = walker;
size++;
}
try using
(walker.next).prev
I might be wrong.
The code is mostly correct. You must add a method for inserting at the start of the list, but from your description/method name, it seems that you insert after a node so there may be no point in adding insertion at the start. You must check for the case when the head node is null. Another sugestion is to return a boolean value if the operation was successful. Another good return can be the newly inserted node or null if the operation failed. You may also throw an exception if you don't wish to return a value.
public class DoubleLinkedList {
private DListNode head;
private DListNode tail;
private int size;
private class DListNode {
private DListNode next;
private DListNode prev;
private int item;
private DListNode(final int item) {
this.item = item;
}
}
public void insertAfterNth(final int n, final int item) {
if (size == 0) {
System.out.println("error: list is empty");
} else if ((n > size) || (n < 1)) {
System.out.println("error: out of bounds");
return;
} else if (n == size) {
insertEnd(item);
}
DListNode walker = head;
int i = 1;
while (i < n) {
i++;
walker = walker.next;
}
DListNode node = new DListNode(item);
node.next = walker.next;
walker.next.prev = node;
walker.next = node;
node.prev = walker;
size++;
}
private void insertEnd(int item) {
size++;
final DListNode newItem = new DListNode(item);
if (head == null) {
head = newItem;
tail = newItem;
} else {
tail.next = newItem;
newItem.prev = tail;
tail = newItem;
}
}
public void add(final int item) {
insertEnd(item);
}
//the rest of operations you wish to implement
}

Categories