C:\Users\ar114\Documents\NetBeansProjects\ProgramingExam2_CalebFontenot\src\main\java\com\mycompany\programingexam2_calebfontenot\ProgramingExam2_CalebFontenot.java |
nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/$
package com.mycompany.programingexam2_calebfontenot;
@author
public class ProgramingExam2_CalebFontenot<T> {
Node<T> head;
Node<T> tail;
class Node<T> {
T t;
Node<T> l;
Node<T> r;
}
public T removeAt(int pos) {
if (pos < 0 || pos > size() - 1) {
throw new IndexOutOfBoundsException();
}
if (size() == 0) {
throw new RuntimeException("The list empty.");
}
T returnT = null;
if (pos == 0)
{
Node<T> pointer = head.r;
returnT = (T) head.t;
pointer.l = null;
head = pointer;
} else if (pos == (size() - 1))
{
Node<T> pointer = tail.l.l;
returnT = (T) tail.t;
pointer.r = null;
tail = pointer;
} else
{
Node<T> pointer = head;
for (int i = 0; i < pos - 1; ++i) {
pointer = pointer.r;
}
pointer.r = pointer.r.r;
pointer.l = pointer.r;
returnT = (T) pointer.t;
}
return returnT;
}
public void clear() {
head = tail = null;
}
public void addAt(T t, int pos) {
if (pos < 0 || pos > size()) {
throw new IndexOutOfBoundsException();
}
Node<T> newNode = new Node<T>();
newNode.t = t;
if (head == null)
{
head = tail = newNode;
} else if (pos == 0)
{
newNode.r = head;
head.l = newNode;
head = newNode;
} else if (pos == size())
{
newNode.l = tail;
tail.r = newNode;
tail = newNode;
} else
{
Node<T> p = head;
for (int i = 0; i < pos - 1; ++i) {
p = p.r;
}
newNode.l = p;
newNode.r = p.r;
p.r.l = newNode;
p.r = newNode;
}
}
public int size() {
Node<T> p = head;
int count = 0;
while (p != null) {
count++;
p = p.r;
}
return count;
}
@Override
public String toString() {
String s = "";
Node<T> p = head;
while (p != null) {
s += p.t.toString() + " ";
p = p.r;
}
return s;
}
public static void main(String[] args) {
ProgramingExam2_CalebFontenot<Integer> list = new ProgramingExam2_CalebFontenot<Integer>();
list.addAt(20, 0);
list.addAt(10, 0);
list.addAt(40, 2);
list.addAt(30, 2);
list.addAt(50, 4);
System.out.println(list);
System.out.println(list.removeAt(0));
System.out.println(list);
System.out.println(list.removeAt(2));
System.out.println(list);
System.out.println(list.removeAt(2));
System.out.println(list.toString());
}
}