import java.util.*;
public class ListStack extends LinkedList{
public ListStack() { // <== constructor, different from ListStackComp.java
super();
}
public boolean empty() {
if(isEmpty()){
return true;
}else{
return false;
}
}
public Object push(Object item) {
addToHead(item);
return item;
}
public Object pop() {
Object item = removeFromHead();
return item;
}
public Object peek() {
Object item = get(0);
return item;
}
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 0;i<length;i++){
if(item.equals(current.getData())){
num = i;
}
else{
current = current.getNext();
}
}
return num;
}
}
The result is:
[ 789.123 E Patrick 123 Dog Cat B A ]
peek() returns: 789.123
Patrick is at 7
A is at 7
789.123 is at 7
Peter is at -1
Can help me to solve the problem? Does search() have some error?
class ListNode {
private Object data;
private ListNode next;
ListNode(Object o) { data = o; next = null; }
ListNode(Object o, ListNode nextNode)
{ data = o; next = nextNode; }
public void setData(Object data){
this.data = data;
}
public void setNext(ListNode next){
this.next = next;
}
public Object getData() { return data; }
public ListNode getNext() { return next; }
} // class ListNode
class EmptyListException extends RuntimeException {
public EmptyListException () { super ("List is empty"); }
} // class EmptyListException
class LinkedList {
protected ListNode head; // <== chnage to protected for inheriting
protected ListNode tail; // <== change to protected for inheriting
protected int length; // the length of the list <== chnage to protected for inheriting
public LinkedList() {
head = tail = null;
length = 0;
}
public boolean isEmpty() { return head == null; }
public void addToHead(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else
head = new ListNode(item, head);
length++;
}
public void addToTail(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else {
tail.setNext(new ListNode(item));
tail = tail.getNext();
}
length++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = head.getData();
if (head == tail)
head = tail = null;
else
head = head.getNext();
length--;
return item;
}
public Object removeFromTail() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = tail.getData();
if (head == tail)
head = tail = null;
else {
ListNode current = head;
while (current.getNext() != tail)
current = current.getNext();
tail = current;
current.setNext(null);
}
length--;
return item;
}
public String toString() {
String str = "[ ";
ListNode current = head;
while (current != null) {
str = str + current.getData() + " ";
current = current.getNext();
}
return str + " ]";
}
public int count() {
return length;
}
public Object remove(int n) {
Object item = null;
if (n <= length) { // make sure there is nth node to remove
// special treatment for first and last nodes
if (n == 1) return removeFromHead();
if (n == length) return removeFromTail();
// removal of nth node which has nodes in front and behind
ListNode current = head;
ListNode previous = null;
for (int i = 1; i < n; i++) { // current will point to nth node
previous = current;
current = current.getNext();
}
// data to be returned
item = current.getData();
// remove the node by adjusting two pointers (object reference)
previous.setNext(current.getNext());
}
length--;
return item;
}
public void add(int n, Object item) {
// special treatment for insert as first node
if (n == 1) {
addToHead(item);
return;
}
// special treatment for insert as last node
if (n > length) {
addToTail(item);
return;
}
// locate the n-1th node
ListNode current = head;
for (int i = 1; i < n-1; i++) // current will point to n-1th node
current = current.getNext();
// create new node and insert at nth position
current.setNext(new ListNode(item, current.getNext()));
length++;
}
public Object get(int n) {
// n is too big, no item can be returned
if (length < n) return null;
// locate the nth node
ListNode current = head;
for (int i = 1; i < n; i++)
current = current.getNext();
return current.getData();
}
} // class LinkedList
import java.util.Stack;
import java.util.Iterator;
public class TestStack {
public static void main (String args[]) {
ListStack s = new ListStack();
System.out.println(s);
System.out.println("Patrick is at " + s.search("Patrick"));
s.push(new Character('A'));
System.out.println(s);
s.push(new Character('B'));
System.out.println(s);
s.push("Cat");
System.out.println(s);
s.push("Dog");
System.out.println(s);
s.push(new Integer(123));
System.out.println(s);
s.push("Patrick");
System.out.println(s);
s.push(new Character('E'));
System.out.println(s);
s.push(new Double(789.123));
System.out.println(s);
System.out.println("peek() returns: " + s.peek());
System.out.println("Patrick is at " + s.search("Patrick"));
System.out.println("A is at " + s.search(new Character('A')));
System.out.println("789.123 is at " + s.search(new Double(789.123)));
System.out.println("Peter is at " + s.search("Peter"));
System.out.println();
}
} // class TestStack
There is another code of LinkedList and Test file
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 0;i<length;i++){
if(item.equals(current.getData())){
return i;
}
else{
current = current.getNext();
}
}
return num;
}
Hope It will work.
public Object peek() {
Object item = get(0);
return item;
}
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 1;i<length;i++){
if(item.equals(current.getData())){
num = i;
return num;
}
else{
current = current.getNext();
}
}
return num;
}
There is new problem in the result:
[ A B Cat Dog 123 Patrick E 789.123 ]
peek() returns: A
Patrick is at 6
A is at 1
789.123 is at -1
Peter is at -1
Why the result cannot find 789.123?
The peek() method how can I improve that can find 789.123 is top?
Related
I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.
Use an inner class for the Node.
Include the methods below.
Write a tester to enable you to test all of the methods with whatever data you want in any order.
I have to create a method called "public LinkedListOfInts reverse()". This method is meant to "Return a copy of your Linked List but in reverse order." I have my code for this method down below. However, when I try to reverse a list it only prints the head. For Example, if I have a list like "[16, 1, 8, 7, 10, 10, 14, 17, 11, 4,] and I try to reverse it my output is [ 16, ]. Does someone know how correct my code so I can reverse a linked list?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
if (head == null)
return null;
Node current = head;
Node previous = null;
Node nextNode = null;
while (current != null) {
nextNode = current.nextNode;
current.nextNode = previous;
previous = current;
current = nextNode;
}
return this;
}
public String toString() {
String result = " ";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result += ptr.value + " ";
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 11:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 12:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
Here is a working example for reversing your LinkedList. Keep in mind that you are not copying the content of the LinkedList. So if you reverse the list, the original list's head is now the tail and returns only one int.
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts{
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
#Override
public String toString() {
return "Node{" +
"value=" + value +
", nextNode=" + nextNode +
'}';
}
}
public LinkedListOfInts(LinkedListOfInts other) {
System.out.println(other.tail);
head = other.head;
tail = other.tail;
System.out.println(this);
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++) {
this.addToFront(random.nextInt(high - low) + low);
}
Node node=head;
while(node.nextNode!=null){
node = node.nextNode;
}
tail = node;
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
Node previous = null;
Node curr = head;
Node nex;
while (curr != null)
{
nex = curr.nextNode;
curr.nextNode = previous;
previous = curr;
curr = nex;
}
head = previous;
return this;
}
public String toString() {
StringBuilder result = new StringBuilder(" ");
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result.append(ptr.value).append(" ");
return result.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 2:
System.out.println("toString");
System.out.println(list);
break;
}
}
}
}
I need your help with implementing the correct sorting algorithm for Priority Queue. Apparently I've done this wrong as it creates a duplicate node. I'm stumped on this, any help would be greatly appreciated. I need to get this right as I will use this on both increase() and decrease() methods.
Check my sort() method below in the code.
Here is my code:
public class PriorityQueueIntegers implements PriorityQueueInterface {
// number of elements
private int numberOfElements;
// element
private int element;
// priority
private int priority;
// Node
Node head = null, tail = null;
// returns true if the queue is empty (no items in queue)
// false if queue is (has at least one or more items in queue)
public boolean isEmpty()
{
return ( numberOfElements == 0 );
}
// returns the value of the item currently at front of queue
public int peek_frontValue()
{
return head.getValue(); // return the value in the head node
}
// returns the priority of the item currently at front of queue
public int peek_frontPriority()
{
return head.getPriority();
}
// clear the queue
public void clear()
{
head = null;
tail = null;
numberOfElements = 0;
}
// insert the item with element and priority
public void insert(int newElement, int newPriority)
{
// if head node is null, make head and tail node contain the first node
if (head == null)
{
head = new Node(newElement, newPriority);
tail=head; // when first item is enqueued, head and tail are the same
}
else
{
Node newNode = new Node(newElement, newPriority);
tail.setNext(newNode);
tail=newNode;
}
sort(newElement, newPriority);
numberOfElements++;
}
public void increase(int findElement, int priority_delta)
{
Node current = head;
if (numberOfElements > 0)
{
while (current != null)
{
if (current.getValue() == findElement)
{
int newPriority = current.getPriority() + priority_delta;
current.setIncreasePriority(newPriority);
}
current = current.getNext();
}
} else throw new UnsupportedOperationException("Empty Queue - increase failed");
}
public void decrease(int findElement, int priority_delta)
{
Node current = head;
if (numberOfElements > 0)
{
while (current != null)
{
if (current.getValue() == findElement)
{
int newPriority = current.getPriority() - priority_delta;
if (newPriority < 0)
{
throw new UnsupportedOperationException("Can't be a negative number");
}
current.setDecreasePriority(newPriority);
}
current = current.getNext();
}
} else throw new UnsupportedOperationException("Empty Queue - increase failed");
}
private void sort(int value, int priority)
{
Node current = head;
int v = value;
int p = priority;
Node temp = new Node(v, p);
if (numberOfElements > 0)
{
while (current != null && current.getNext().getPriority() < p)
{
current = current.getNext();
}
temp._next = current._next;
current._next = temp;
}
}
public int remove_maximum()
{
int headDataValue = 0;
if ( numberOfElements > 0 )
{
headDataValue = head.getValue();
Node oldHead=head;
head=head.getNext();
oldHead.setNext(null);
this.numberOfElements--;
}
else throw new UnsupportedOperationException("Empty Queue - dequeue failed");
return headDataValue; // returns the data value from the popped head, null if queue empty
}
public String display()
{
Node current = head;
String result = "";
if ( current == null )
{
result = "[Empty Queue]";
}
else
{
while ( current != null )
{
result = result + "[" + current.getValue() + "," + current.getPriority() + "] ";
current = current.getNext();
}
}
return result;
}
//////////////////////////////////////////////////////////////
// Inner Node Class
private class Node
{
private int value;
private int priority;
private Node _next;
public Node (int element, int priority_delta)
{
this.value = element;
this.priority = priority_delta;
_next = null;
}
protected Node(int element, int priority_delta, Node nextNode)
{
this.value = element;
this.priority = priority_delta;
_next = nextNode;
}
public Node getNext()
{
return _next;
}
public int getValue()
{
return this.value;
}
public int getPriority()
{
return this.priority;
}
public void setIncreasePriority(int newPriority)
{
this.priority = newPriority;
}
public void setDecreasePriority(int newPriority)
{
this.priority = newPriority;
}
public void setNext(Node newNextNode)
{
_next = newNextNode;
}
}
}
You are correct that your code currently creates duplicate nodes. Your insert method creates a node:
if (head == null) {
head = new Node(newElement, newPriority);
tail=head; // when first item is enqueued, head and tail are the same
} else {
Node newNode = new Node(newElement, newPriority);
tail.setNext(newNode);
tail=newNode;
}
This method then calls sort that also creates a node:
Node temp = new Node(v, p);
if (numberOfElements > 0) {
while (current != null && current.getNext().getPriority() < p) {
current = current.getNext();
}
temp._next = current._next;
current._next = temp;
}
It does not make a lot of sense to me that a sort method would create a new node. You should either insert the node in the right position in insert or the sort method should move it to the correct position. If you take the first approach then you'll need to change you increase and decrease methods.
A potential method to move a node to the correct position, in pseduocode, would be:
move node:
walk through queue and find both
node that's next points to the one you are moving (from)
last node that has higher priority than the one you are moving (to)
set from.next to node.next
set node.next to to.next
set to.next to node
On my count method, i am trying to compare the object being sent with the object calling it, and I have no idea why i can not cal o.get(i) to get the value for Object o being passed. It tells me the method cannot be found even though i can call get(i) normally. Any ideas how i can get the value for the object getting passed so i can compare them?
public class GenericLinkedList<E> implements List<E> {
private class Node<E>{
private E data;
private Node<E> next;
}
private E data;
private Node<E> head = null;
private int size = 0;
private Node<E> nodeAt(int index){
Node<E> curNode = head;
int curIndex = 0;
while(curIndex < index){
curNode = curNode.next;
curIndex++;
}
return curNode;
}
#Override
public E get(int index) {
return nodeAt(index).data;
}
#Override
public void add(E value) {
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else{
Node<E> curNode = nodeAt(size - 1);
curNode.next = node;
}
size++;
}
public void add(int index, E value){
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else if(index == 0){
node.next = head;
head = node;
}else{
Node<E> curNode = nodeAt(index - 1);
node.next = curNode.next;
curNode.next = node;
}
size++;
}
#Override
public void remove(int index) {
if(index == 0){
head = head.next;
}else{
Node<E> curNode = nodeAt(index - 1);
curNode.next = curNode.next.next;
}
size--;
}
#Override
public void set(int index, E value) {
nodeAt(index).data = value;
}
public String toString(){
String s = "";
Node<E> curNode = head;
s += curNode.data +" -> ";
while(curNode.next != null){
curNode = curNode.next;
s += curNode.data +" -> ";
}
s += "null";
return s;
}
public void clear() {
for (int i = 0; i < size; i++)
set(i, null);
size = 0;
}
#Override
public void removeAll(E o)//Clears out the array object by setting everything to null
{
for(int i = 0; i < this.size; i++)
{
}
}
#Override
public int count(Object o)
{
System.out.println(o);
int count = 0;
for(int i = 0; i< size;i++)
{
if(get(i) == o.get(i))
{
count++;
}
}
return count;
/*int count = 0;
for(int i = 0;i<this.size;i++)
{
for(int j = 0;i<size;j++)
{
}
}
return count;*/
}
public void reverse()
{
int x = size;
for(int i = 0; i < this.size; i++)
{
E temp = this.get(x);
this.set(x, get(i));
this.set(i, temp);
x++;
}
}
public Object subList(int beginIndex, int endIndex)
{
int j = 0;
GenericLinkedList<E> LinkedList = new GenericLinkedList<E>();
if(beginIndex == endIndex)
return LinkedList;
else if(beginIndex > endIndex||endIndex>size||beginIndex<0)
{
return null;
}
else
{
for(int i = beginIndex; i <= endIndex;i++)
{
LinkedList.add(get(i));
j++;
}
}
return LinkedList;
}
public static void main(String[] args) {
GenericLinkedList<Integer> myList = new GenericLinkedList<Integer>();
myList.add(4);
myList.add(7);
myList.add(123123);
System.out.println(myList.get(2));
GenericLinkedList<Integer> myList2 = new GenericLinkedList<Integer>();
myList2.add(4);
myList2.add(7);
myList2.add(8);
myList2.add(3,999);
System.out.println(myList2);
System.out.println(myList.count(myList2));
//System.out.println(myList2);
// myList2.clear();//Testing our clear class
// System.out.println(myList2);
//System.out.println(myList2.subList(1, 3));//Testing our clear class
// System.out.println(myList2);
}
}
You have a problem when trying to call o.get() because it is an object of the base type Object which has no method get defined. To get the proper result you have two possible solutions....
The short solution is to type cast.
((GenericLinkedList<Object>)o).get(i)
Or a more easily readable solution is to change the signature of your count method:
public int count(GenericLinkList<E> list) {
...
}
Change your count method to public int GenericLinkedList(Object o)
If you use Object as the type of the parameter, you can only call the methods which are available on Object.
I'm struggling to construct a Linked List object for building strings. My class LString is meant to mimic a String or StringBuilderobject. Instead of arrays, it uses a linked list to form strings. I'm unsure of how to form the constructor though.
Here is my code so far:
public class LString {
// 2. Fields
node front;
//node tail;
int size;
// 1. Node class
private class node {
char data;
node next;
//constructors
//1. default
public node (){
}
//2. data
public node (char newData){
this.data = newData;
}
//3. data + next
public node (char newData, node newNext){
this.data = newData;
this.next = newNext;
}
}
// 3. Constructors
public LString(){
this.size = 0;
this.front = null;
}
public LString(String original) {
}
// 4. Methods
public int length() {
return this.size;
}
public int compareTo(LString anotherLString) {
return 0;
}
public boolean equals(Object other) {
if (other == null || !(other instanceof LString)) {
return false;
}
else {
LString otherLString = (LString)other;
return true;
}
}
public char charAt(int index) {
return 'a';
}
public void setCharAt(int index, char ch) {
ch = 'a';
}
public LString substring(int start, int end) {
return null;
}
public LString replace(int start, int end, LString lStr) {
return null;
}
//append
public void append (char data){
this.size++;
if (front == null){
front = new node(data);
return;
}
node curr = front;
while (curr.next != null){
curr = curr.next;
}
curr.next = new node(data);
}
//prepend
public void prepend (char data){
/*node temp = new node(data);
temp.next = front;
front = temp;*/
front = new node(data, front);
size++;
}
//delete
public void delete(int index){
//assume that index is valid
if (index == 0){
front = front.next;
} else {
node curr = front;
for (int i = 0; i < index - 1; i++){
curr = curr.next;
}
curr.next = curr.next.next;
}
size--;
}
//toString
public String toString(){
StringBuilder result = new StringBuilder();
result.append('[');
node curr = front;
while (curr != null){
result.append(curr.data);
if (curr.next != null){
result.append(',');
}
curr = curr.next;
}
result.append(']');
return result.toString();
}
//add (at an index)
public void add(int index, char data){
if (index == 0){
front = new node(data, front);
} else {
node curr = front;
for (int i = 0; i < index - 1; i++){
curr = curr.next;
}
curr.next = new node(data, curr.next);
}
}
}
Many of the methods are stubs, so the class will compile with another test file. I don't think I need to include it to find the issue though.
Thanks for the help.
You can build your LString constructor in different ways. One way I can think of is to accepting char[] and store it in your internal LinkedList. You can take a look at String constructors in here to get more ideas.
I'm trying to work on a method that will insert the node passed to it before the current node in a linked list. It has 3 conditions. For this implementation there cannot be any head nodes (only a reference to the first node in the list) and I cannot add any more variables.
If the list is empty, then set the passed node as the first node in the list.
If the current node is at the front of the list. If so, set the passed node's next to the current node and set the first node as the passed node to move it to the front.
If the list is not empty and the current is not at the front, then iterate through the list until a local node is equal to the current node of the list. Then I carry out the same instruction as in 2.
Here is my code.
public class LinkedList
{
private Node currentNode;
private Node firstNode;
private int nodeCount;
public static void main(String[] args)
{
LinkedList test;
String dataTest;
test = new LinkedList();
dataTest = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); }
System.out.println("[1] "+ test);
for(int i=0; i< dataTest.length(); i++) { test.deleteCurrentNode(); }
System.out.println("[2] "+test);
for(int i=0; i< dataTest.length(); i++)
{
test.insertBeforeCurrentNode(new String(new char[] { dataTest.charAt(i) }));
if(i%2 == 0) { test.first(); } else { test.last(); }
}
System.out.println("[3] "+test);
}
public LinkedList()
{
setListPtr(null);
setCurrent(null);
nodeCount = 0;
}
public boolean atEnd()
{
checkCurrent();
return getCurrent().getNext() == null;
}
public boolean isEmpty()
{
return getListPtr() == null;
}
public void first()
{
setCurrent(getListPtr());
}
public void next()
{
checkCurrent();
if (atEnd()) {throw new InvalidPositionInListException("You are at the end of the list. There is no next node. next().");}
setCurrent(this.currentNode.getNext());
}
public void last()
{
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");}
while (!atEnd())
{
setCurrent(getCurrent().getNext());
}
}
public Object getData()
{
return getCurrent().getData();
}
public void insertBeforeCurrentNode(Object bcNode) //beforeCurrentNode
{
Node current;
Node hold;
boolean done;
hold = allocateNode();
hold.setData(bcNode);
current = getListPtr();
done = false;
if (isEmpty())
{
setListPtr(hold);
setCurrent(hold);
}
else if (getCurrent() == getListPtr())
{
System.out.println("hi" + hold);
hold.setNext(getCurrent());
setListPtr(hold);
}
else //if (!isEmpty() && getCurrent() != getListPtr())
{
while (!done && current.getNext() != null)
{
System.out.println("in else if " + hold);
if (current.getNext() == getCurrent())
{
//previous.setNext(hold);
//System.out.println("hi"+ "yo" + " " + getListPtr());
hold.setNext(current.getNext());
current.setNext(hold);
done = true;
}
//previous = current;
current = current.getNext();
}
}
System.out.println(getCurrent());
}
public void insertAfterCurrentNode(Object acNode) //afterCurrentNode
{
Node hold;
hold = allocateNode();
hold.setData(acNode);
if (isEmpty())
{
setListPtr(hold);
setCurrent(hold);
//System.out.println(hold + " hi");
}
else
{
//System.out.println(hold + " hia");
hold.setNext(getCurrent().getNext());
getCurrent().setNext(hold);
}
}
public void insert(Object iNode)
{
insertAfterCurrentNode(iNode);
}
public Object deleteCurrentNode()
{
Object nData;
Node previous;
Node current;
previous = getListPtr();
current = getListPtr();
nData = getCurrent().getData();
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");}
else if (previous == getCurrent())
{
getListPtr().setNext(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount - 1;
}
else
{
while (previous.getNext() != getCurrent())
{
previous = current;
current = current.getNext();
}
previous.setNext(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount - 1;
}
return nData;
}
public Object deleteFirstNode(boolean toDelete)
{
if (toDelete)
{
setListPtr(null);
}
return getListPtr();
}
public Object deleteFirstNode()
{
Object deleteFirst;
deleteFirst = deleteFirstNode(true);
return deleteFirst;
}
public int size()
{
return this.nodeCount;
}
public String toString()
{
String nodeString;
Node sNode;
sNode = getCurrent();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
private Node allocateNode()
{
Node newNode;
newNode = new Node();
nodeCount = nodeCount + 1;
return newNode;
}
private void deAllocateNode(Node dNode)
{
dNode.setData(null);
}
private Node getListPtr()
{
return this.firstNode;
}
private void setListPtr(Node pNode)
{
this.firstNode = pNode;
}
private Node getCurrent()
{
return this.currentNode;
}
private void setCurrent(Node cNode)
{
this.currentNode = cNode;
}
private void checkCurrent()
{
if (getCurrent() == null) {throw new InvalidPositionInListException("Current node is null and is set to an invalid position within the list! checkCurrent()");}
}
/**NODE CLASS ----------------------------------------------*/
private class Node
{
private Node next; //serves as a reference to the next node
private Object data;
public Node()
{
this.next = null;
this.data = null;
}
public Object getData()
{
return this.data;
}
public void setData(Object obj)
{
this.data = obj;
}
public Node getNext()
{
return this.next;
}
public void setNext(Node nextNode)
{
this.next = nextNode;
}
public String toString()
{
String nodeString;
Node sNode;
sNode = getCurrent();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
}
}
I have it working for my [1] and [2] conditions. But my [3] (that tests insertBeforeCurrentNode()) isn't working correctly. I've set up print statements, and I've determined that my current is reset somewhere, but I can't figure out where and could use some guidance or a solution.
The output for [1] and [2] is correct. The output for [3] should read
[3] List contains 26 nodes: z x v t r p n l j h f d b c e g i k m o q s u w y a
Thanks for any help in advance.
In your toString method you start printing nodes from the currentNode till the end of your list. Because you call test.last() just before printing your results, the currentNode will point on the last node of the list, and your toString() will only print 'a'.
In your toString() method, you may want to change
sNode = getCurrent();
with
sNode = getListPtr();
to print your 26 nodes.
For [3] you need to keep pointers to two nodes: one pointer in the "current" node, the one you're looking for, and the other in the "previous" node, the one just before the current. In that way, when you find the node you're looking in the "current" position, then you can connect the new node after the "previous" and before the "current". In pseudocode, and after making sure that the cases [1] and [2] have been covered before:
Node previous = null;
Node current = first;
while (current != null && current.getValue() != searchedValue) {
previous = current;
current = current.getNext();
}
previous.setNext(newNode);
newNode.setNext(current);