I have posted this code several times I apologize if you keep looking at this question. I've been working on this for a bit so any help would be helpful i've done as much as I can so far. But when my program prints the data it switches the 8 and the 7 around and I can't figure out why! Here is all the code. And I have not started making my remove method yet so disregard that functionality.
public class MyLinkedList<AnyType> implements Iterable<AnyType> {
private int theSize;
private Node<AnyType> beginMarker;
private Node<AnyType> endMarker;
public class Node<AnyType> {
public Node(AnyType data, Node<AnyType> head, Node<AnyType> tail) {
myData = data;
myHead = head;
myTail = tail;
}
public AnyType myData;
public Node<AnyType> myHead;
public Node<AnyType> myTail;
}
public MyLinkedList() {
beginMarker = new Node(null, endMarker, null);
endMarker = new Node(null, null, beginMarker);
theSize = 0;
}
public void clear() {
beginMarker.myHead = endMarker;
endMarker.myTail = beginMarker;
}
public int size() {
return theSize;
}
public boolean exist(AnyType newVal) {
beginMarker.myHead.myData = newVal;
if (newVal != null) {
return true;
}
return false;
}
private void addBefore(Node<AnyType> previousNode, AnyType newNode) {
Node<AnyType> new_node = new Node<>(newNode, previousNode.myTail, previousNode);
new_node.myTail.myHead = new_node;
previousNode.myTail = new_node;
theSize++;
}
public boolean add(AnyType newVal) {
{
add(size(), newVal);
return true;
}
}
public boolean add(int index, AnyType newVal) {
addBefore(getNode(index, 0, size()), newVal);
return true;
}
private Node<AnyType> getNode(int index) {
return getNode(index, 0, size() - 1);
}
public Node<AnyType> get(AnyType nodeData) {
Node<AnyType> node = beginMarker;
while (node != endMarker) {
// Means node.data = nodeData
if (node.myData.equals(nodeData)) {
return node;
}
}
return null;
}
// Added method
private Node<AnyType> getNode(int index, int lower, int upper) {
Node<AnyType> x;
if (index < lower || index > upper)
throw new IndexOutOfBoundsException();
if (index < size() / 2) {
x = beginMarker.myHead;
for (int i = 0; i < index; i++)
x = x.myHead;
} else {
x = endMarker.myTail;
for (int i = size(); i > index; i--) {
x = x.myTail;
}
}
return x;
}
public void printList() {
Node temp = beginMarker.myHead;
while (temp != null) {
System.out.println(temp.myData);
temp = temp.myHead;
}
}
public java.util.Iterator<AnyType> iterator() {
return new LinkedListIterator();
}
public void remove(AnyType removeVal) {
/*
* if(node.myData.equals(nodeData))
*
* MyLinkedList testList = new MyLinkedList();
*
* Node temp = testList.beginMarker.myData; while(temp != null){
*
* if(temp == removeVal){ temp.myTail = temp.myHead; temp.myHead =
* temp.myTail; } else{ temp.myHead = temp; }
*
*
* }
*/
}
private class LinkedListIterator implements java.util.Iterator<AnyType> {
private Node<AnyType> node_ = beginMarker;
public void remove() {
}
public boolean hasNext() {
if (node_.myHead != null) {
return true;
}
return false;
}
public AnyType next() {
if (!hasNext()) {
return null;
}
node_ = node_.myHead;
return node_.myData;
}
}
private static void testListIntegers() {
MyLinkedList<Integer> testList = new MyLinkedList<Integer>();
testList.add(new Integer(5));
testList.add(new Integer(4));
testList.add(new Integer(3));
System.out.println(" We have so far inserted " + testList.size() + " elements in the list");
testList.remove(4);
System.out.println(" Now, there is only " + testList.size() + " elements left in the list");
testList.add(1, new Integer(7));
testList.add(2, new Integer(8));
System.out.println(" About to print content of the list");
testList.printList();
}
private static void testListStrings() {
MyLinkedList<String> testList = new MyLinkedList<String>();
testList.add(new String("hello"));
testList.add(new String("this is"));
testList.add(new String("cs3345 project 2"));
System.out.println(" We have so far inserted " + testList.size() + " elements in the list");
testList.remove("this is");
System.out.println(" Now, there is only " + testList.size() + " elements left in the list");
testList.add(1, "a modified version of");
testList.add(2, "cs3345 project 2, call it version 2");
System.out.println(" About to print content of the list");
testList.printList();
}
public static void main(String args[]) throws Exception {
// Add whatever code you need here
// However, you will need to call both testListIntegers()
// and testListStrings()
testListIntegers();
testListStrings();
}
}
The output is as follows:
We have so far inserted 3 elements in the list
Now, there is only 3 elements left in the list
About to print content of the list
8
7
3
4
5
We have so far inserted 3 elements in the list
Now, there is only 3 elements left in the list
About to print content of the list
cs3345 project 2, call it version 2
a modified version of
cs3345 project 2
this is
hello
Problem is with addBefore method:
private void addBefore(Node<AnyType> previousNode, AnyType newNode) {
Node<AnyType> new_node = new Node<>(newNode, previousNode.myTail, previousNode);
new_node.myTail.myHead = new_node;
previousNode.myTail = new_node;
theSize++;
}
It is the same like:
private void addBefore(Node<AnyType> previousNode, AnyType newNode) {
Node<AnyType> new_node = new Node<>(newNode, previousNode.myTail, previousNode);
previousNode.myHead = new_node;
previousNode.myTail = new_node;
theSize++;
}
So basically you are breaking doubly linked list.
Edit:
According to algorithm described here this method should look like:
private void addBefore(Node<AnyType> previousNode, AnyType newNode) {
Node<AnyType> new_node = new Node<>(newNode, previousNode, previousNode.myTail);
if(previousNode.myTail==null){
beginMarker.myHead = new_node;
} else {
previousNode.myTail.myHead = new_node;
}
previousNode.myTail = new_node;
theSize++;
}
See that your list is indexed from 0 so the output should be:
5
7
8
4
3
And next problem is in printList method (infinite loop) because somewhere is wrong usage of your begin/end marker.
adding theSize--; at the end of the remove method should decrease the elements from 3 to 1
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;
}
}
}
}
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?
I am trying to make an application that will loop through a circular linked list. As it does so, it will use another linked list of index values, and it will use these values to delete from the circular linked list.
I have it set up now where it should fetch the index value to be deleted from my random linked list via runRandomList() method. It then uses the rotate() method to loop through the circular linked list and deletes the value from it. It will then add the deleted value to "deletedLinked list". Then, control should return back to runRandomList() method and it should feed the rotate() method the next value from the random linked list. The circular linked list should begin traversing where it left off. It should keep track of the count and node it is on. The count should reset to 0 when it reaches the first node, so it can properly keep track of which index it is on.
Unfortunately, this is not happening. I have been trying different things for the last few days as the code stands right now; it enters into a continuous loop. the issue appears to be in the rotate method.
This is the rotate method code. My thought was the counter would advance until it matches the index input. If it reaches the first node, the counter would reset to 0 and then start to increment again until it reaches the index value.
private void rotate(int x)
{
while(counter <= x)
{
if(p == names.first)
{
counter = 0;
}
p = p.next;
counter++;
}
deleteList.add((String) p.value);
names.remove(x);
}
This is my linked list class:
public class List<T>{
/*
helper class, creates nodes
*/
public class Node {
T value;
Node next;
/*
Inner class constructors
*/
public Node(T value, Node next)
{
this.value = value;
this.next = next;
}
private Node(T value)
{
this.value = value;
}
}
/*
Outer class constructor
*/
Node first;
Node last;
public int size()
{
return size(first);
}
private int size(Node list)
{
if(list == null)
return 0;
else if(list == last)
return 1;
else
{
int size = size(list.next) + 1;
return size;
}
}
public void add(T value)
{
first = add(value, first);
}
private Node add(T value, Node list)
{
if(list == null)
{
last = new Node(value);
return last;
}
else
list.next = add(value, list.next);
return list;
}
public void setCircularList()
{
last.next = first;
}
public void show()
{
Node e = first;
while (e != null)
{
System.out.println(e.value);
e = e.next;
}
}
#Override
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + "\n");
p = p.next;
}
return strBuilder.toString();
}
public boolean isEmpty()
{
boolean result = isEmpty(first);
return result;
}
private boolean isEmpty(Node first)
{
return first == null;
}
public class RemovalResult
{
Node node; // The node removed from the list
Node list; // The list remaining after the removal
RemovalResult(Node remNode, Node remList)
{
node = remNode;
list = remList;
}
}
/**
The remove method removes the element at an index.
#param index The index of the element to remove.
#return The element removed.
#exception IndexOutOfBoundsException When index is
out of bounds.
*/
public T remove(int index)
{
// Pass the job on to the recursive version
RemovalResult remRes = remove(index, first);
T element = remRes.node.value; // Element to return
first = remRes.list; // Remaining list
return element;
}
/**
The private remove method recursively removes
the node at the given index from a list.
#param index The position of the node to remove.
#param list The list from which to remove a node.
#return The result of removing the node from the list.
#exception IndexOutOfBoundsException When index is
out of bounds.
*/
private RemovalResult remove(int index, Node list)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if (index == 0)
{
// Remove the first node on list
RemovalResult remRes;
remRes = new RemovalResult(list, list.next);
list.next = null;
return remRes;
}
// Recursively remove the element at index-1 in the tail
RemovalResult remRes;
remRes = remove(index-1, list.next);
// Replace the tail with the results and return
// after modifying the list part of RemovalResult
list.next = remRes.list;
remRes.list = list;
return remRes;
}
}
This contains the main(), runRandomList(), and rotate() methods.
public class lottery {
private int suitors;
private List<String> names;
private List<Integer> random;
private List<String> deleteList = new List<>();
private int counter;
private Node p;
public lottery(int suitors, List<String> names, List<Integer> random)
{
this.suitors = suitors;
this.names = names;
this.random = random;
p = names.first;
}
public void start()
{
//Set names list to circular
names.setCircularList();
runRandomList(random);
}
public void runRandomList(List<Integer> random)
{
Node i = random.first;
while(i != null)
{
rotate((int) i.value, counter, p);
i = i.next;
}
}
public List getDeleteList()
{
return deleteList;
}
private void rotate(int x, int count, Node p)
{
Node i = p;
while(count <= x)
{
if(i == names.first)
{
count = 0;
}
i = i.next;
count++;
}
deleteList.add((String) i.value);
names.remove(x);
p = i;
counter = count;
}
public static void main(String[] args)
{
List<String> namesList = new List<>();
namesList.add("a");
namesList.add("b");
namesList.add("c");
namesList.add("d");
namesList.add("e");
namesList.add("f");
List<Integer> randomList = new List<>();
randomList.add(3);
randomList.add(1);
randomList.add(5);
randomList.add(4);
randomList.add(0);
lottery obj = new lottery(6, namesList, randomList);
obj.start();
System.out.println(obj.getDeleteList());
}
}
As I suspected it was the rotate method, this is the solution.
private void rotate(int x, int count)
{
while(count != x)
{
p = p.next;
count++;
if(count == x)
{
deleteList.add((String)p.value);
counter = x;
}
if(count >= suitors)
{
for (int j = 0; j < x ; j++)
{
p = p.next;
}
deleteList.add((String)p.value);
counter = x;
count = x;
}
}
}
I expect the DFS method to print the path as 1->2->4->5 but it shows 1->2->3->4->5 can you please hint how the method can be fixed with the least amount of code addendum?
/**
* Created by mona on 5/28/16.
*/
import java.util.Stack;
public class DepthFirstSearch {
public static void DFS(GraphNode root, int num) {
if (root.val == num) {
System.out.println("root has the value "+num);
}
System.out.println(" current value is "+root.val);
Stack<GraphNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
for (GraphNode g : stack.pop().neighbors) {
if (!g.visited) {
System.out.println(" current value is "+g.val);
if (g.val == num) {
System.out.println("Found");
}
g.visited = true;
stack.push(g);
}
}
}
}
public static void main(String[] args) {
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
n1.neighbors = new GraphNode[] {n2};
n2.neighbors = new GraphNode[] {n4,n3};
n3.neighbors = new GraphNode[] {n4};
n4.neighbors = new GraphNode[] {n5};
n5.neighbors = new GraphNode[] {};
DFS(n1, 5);
}
}
Here's the code for GraphNode class:
/**
* Created by mona on 5/27/16.
*/
public class GraphNode {
int val;
GraphNode next;
GraphNode[] neighbors;
boolean visited;
GraphNode(int val) {
this.val = val;
this.visited = false;
}
GraphNode(int val, GraphNode[] neighbors) {
this.val = val;
this.neighbors = neighbors;
this.visited = false;
}
public String toString() {
return "value is: "+this.val;
}
}
To get a path to the node, it's insufficient to just add all the nodes that you encounter, since you could run into a "dead end" in the graph or add nodes not actually on the path. To prevent this you need to keep track of the nodes that contained a node as neighbor when you inserted them to the stack:
Map<GraphNode, GraphNode> parents = new HashMap<>();
outer: while (!stack.isEmpty()) {
GraphNode currentElement = stack.pop();
for (GraphNode g : currentElement.neighbors) {
if (!g.visited) {
parents.put(g, currentElement);
System.out.println(" current value is "+g.val);
if (g.val == num) {
System.out.println("Found");
List<GraphNode> path = reconstructPath(parents, g);
// use path, e.g.
System.out.println(path.stream().map(n -> Integer.toString(n.val)).collect(Collectors.joining("->")));
break outer;
}
g.visited = true;
stack.push(g);
}
}
}
static List<GraphNode> reconstructPath(Map<GraphNode, GraphNode> parents, GraphNode end) {
List<GraphNode> list = new ArrayList<>();
while (end != null) {
list.add(end);
end = parents.get(end);
}
Collections.reverse(list);
return list;
}
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);