Java Linked list-NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
so I am having a few errors in my code but Im not sure what they are telling me to change. This is my first linked list code. If anyone can help me out i would appreciate it.
This is my linked list
public class MyLinkedList<E>
{
private Node<E> head = null;
public void add(E element)
{
if(size() == 0)
{
head = new Node<E>(element);
return;
}
Node<E> cursor = head;
while (cursor.next != null)
{
cursor = cursor.next;
}
cursor.next = new Node<E>(element);
}
public void add(int index, E element)
{
Node<E> cursor = head;
E temp, before;
for(int x = 0; x < index; x++)
{
cursor = cursor.next;
}
before = cursor.content;
cursor.content = element;
while(cursor.next != null)
{
cursor = cursor.next;
temp = cursor.content;
cursor.content = before;
before = temp;
}
add(before);
}
public boolean remove(E element)
{
Node<E> cursor = head;
if (head.content == element)
{
head = cursor.next;
return true;
}
while(cursor.next != null)
{
if (cursor.next.content == element)
{
cursor.next = cursor.next.next;
}
else
{
cursor = cursor.next;
}
}
if (cursor.next == null)
{
return false;
}
return true;
}
public E remove(int index)
{
E result = null;
if (index < 0 || index >= size())
{
return null;
}
Node<E> cursor = head;
for (int x = 0; x < index; x++)
{
cursor = cursor.next;
}
result = cursor.content;
cursor = head;
for (int x = 0; x < index - 1; x++)
{
cursor = cursor.next;
}
if(index != 0)
{
cursor.next = cursor.next.next;
}
else
{
head = cursor.next;
}
return result;
}
public E set(int index, E element)
{
Node<E> cursor = head;
E temp;
for (int x = 0; x < index; x++)
{
cursor = cursor.next;
}
temp = cursor.content;
cursor.content = element;
return temp;
}
public boolean contains(E element)
{
Node<E> cursor = head;
while(cursor != null)
{
if(cursor.content == element)
{
return true;
}
cursor = cursor.next;
}
return false;
}
public E get(int index)
{
Node<E> cursor = head;
if (index < 0 || index >= size())
{
return null;
}
for (int x = 0; x < index; x++)
{
cursor = cursor.next;
}
return cursor.content;
}
public int indexOf(E element)
{
Node<E> cursor = head;
int index = 0;
while (cursor != null)
{
if(cursor.content == element)
{
return index;
}
index++;
cursor = cursor.next;
}
return -1;
}
public boolean isEmpty()
{
if (size() == 0)
{
return true;
}
return false;
}
public int size()
{
Node<E> cursor = head;
int count = 0;
while (cursor != null)
{
count++;
cursor = cursor.next;
}
return count;
}
public void dumpList()
{
Node<E> cursor = head;
while (cursor != null)
{
System.out.println(cursor.content);
cursor = cursor.next;
}
}
}
This is my node code
public class Node<E>
{
public E content;
public Node<E> next;
public Node(E content)
{
this.content = content;
}
public Node(E content, Node<E> next)
{
this(content);
this.next = next;
}
public String toString()
{
return content.toString();
}
}
and this is the code we are testing it with
public class Demo4
{
public static void main(String[] args)
{
MyLinkedList<String> t = new MyLinkedList<String>();
t.add("Santa Maria");
t.add("Los Angeles");
t.add("Ventura");
t.add("Thousand Oaks");
t.add(0, "Orcutt");
t.add(5, "Pismo");
t.add(3, "San Luis Obispo");
t.set(1, "London");
t.set(0, "San Diego");
t.set(6, "Tokyo");
t.add("Westlake");
t.remove("Santa Maria");
System.out.println("was Tokyo found? " + t.remove("Tokyo"));
t.remove("Westlake");
System.out.println("was Dubai found? " + t.remove("Dubai"));
t.remove("Pismo");
System.out.println("Remove index 5. It contained: " + t.remove(5));
System.out.println("Remove index 0. It contained: " + t.remove(0));
System.out.println("Remove index 2. It contained: " + t.remove(2));
System.out.println("Here's what's left over");
for (int x = 0; x < t.size(); x++)
{
System.out.println(t.get(x));
}
System.out.println("--------");
System.out.println("Cool! I didn't crash!");
}
}
my error in eclipse is the following
Exception in thread "main" java.lang.NullPointerException
at MyLinkedList.add(MyLinkedList.java:35)
at MyLinkedListDemo.main(MyLinkedListDemo.java:12)

See, Eclipse is telling you everything a human can tell you :)
this is your error:
Exception in thread "main" java.lang.NullPointerException
at MyLinkedList.add(MyLinkedList.java:35)
at MyLinkedListDemo.main(MyLinkedListDemo.java:12)
Eclipse says "there is a Null Pointer Exception" in line no 35 of the file MyLinkedList.java, when the add() method is called. This was actually invoked my the main() of MyLinkedListDemo.java in line no 12.
Now put a debug point on that line, and you see what is null and why it is null.
You get a NPE, when you try to invoke something on null

You are getting a null pointer exception because you are trying to insert value to a position that doesn't exist in the memory. Remove the lines that add to index 5 and 6 and your code will work.
public class Demo4 {
public static void main(String[] args) {
MyLinkedList<String> t = new MyLinkedList<String>();
t.add("Santa Maria");
t.add("Los Angeles");
t.add("Ventura");
t.add("Thousand Oaks");
t.add(0, "Orcutt");
t.add(3, "San Luis Obispo");
t.set(1, "London");
t.set(0, "San Diego");
t.add("Westlake");
t.remove("Santa Maria");
System.out.println("was Tokyo found? " + t.remove("Tokyo"));
t.remove("Westlake");
System.out.println("was Dubai found? " + t.remove("Dubai"));
t.remove("Pismo");
System.out.println("Remove index 5. It contained: " + t.remove(5));
System.out.println("Remove index 0. It contained: " + t.remove(0));
System.out.println("Remove index 2. It contained: " + t.remove(2));
System.out.println("Here's what's left over");
for (int x = 0; x < t.size(); x++) {
System.out.println(t.get(x));
}
System.out.println("--------");
System.out.println("Cool! I didn't crash!");
}
}

Related

Node class is an internal class in my code?

I'm asked this question and I'm not really sure what it means,
In our LinkedList class, the Node class is an internal class. Briefly
describe two things that would have to be coded differently if the
Node class was a separate class from the LinkedList class.
Here's the code for my LinkedList class:
public class LinkedList<T> implements LinkedListInterface<T> {
private Node head;
private Node tail;
private int count;
public LinkedList() {
head = null;
tail = null;
count = 0;
}
class Node {
T data;
Node next;
Node(T data) {
this.data = data;
next = null;
}
}
public Node getHead() {
return head;
}
public int add(T item) {
Node newNode = new Node(item);
if (isEmpty()) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
count++;
return count;
}
public void add(T item, int pos) throws ListException {
if (pos < 1 || pos > count + 1) {
throw new ListException("Invalid position to insert at");
}
Node newNode = new Node(item);
if (count == 0) {
add(item);
} else if (pos == count + 1) {
add(item);
} else if (pos == 1) {
newNode.next = head;
head = newNode;
count++;
} else {
Node prev = jump(pos - 2);
newNode.next = prev.next;
prev.next = newNode;
count++;
}
}
private Node jump(int numJumps) {
Node nd = head;
for (int i = 0; i < numJumps; i++) {
nd = nd.next;
}
return nd;
}
public LinkedList<T> combine(LinkedList<T> obj2) {
Node list1 = this.getHead();
Node list2 = obj2.getHead();
if (list2 == null) {
return this;
}
if(list1==null) {
return obj2;
}
Node temp=list1;
while(temp.next!=null) {
temp = temp.next;
}
temp.next=list2;
return this;
}
public int contains(T item) {
Node nd = this.head;
for (int pos = 1; pos <= count; pos++) {
if (nd.data.equals(item)) {
return pos;
}
nd = nd.next;
}
return 0;
}
public LinkedList<T> copy() {
LinkedList<T> l = new LinkedList<T>();
try {
for (int pos = 1; pos <= count; pos++)
l.add(retrieve(pos));
}
catch(ListException e) {
System.out.println("Should not occur (Copy)");
}
return l;
}
public boolean equals(Object list) {
if (list == null) {
return false;
}
LinkedList myLinkedList = (LinkedList)list;
if(myLinkedList.getClass() != this.getClass()) {
return false;
}
if(myLinkedList.length() != this.length()) {
return false;
}
try{
for (int pos = 1; pos <= count; pos++) {
if(!myLinkedList.retrieve(pos).equals(this.retrieve(pos))) {
return false;
}
}
}
catch (ListException e) {
System.out.println("Should not occur");
}
return true;
}
public boolean isEmpty() {
return length() == 0;
}
public int length() {
return count;
}
#SuppressWarnings("unchecked")
public T remove(int pos) throws ListException {
if (pos < 1 || pos > count) {
throw new ListException("Invalid position to remove from");
}
Node removedItem = null;
if (count == 1) {
removedItem = head;
head = null;
tail = null;
} else if (pos == 1) {
removedItem = head;
head = head.next;
} else if (pos == count) {
removedItem = tail;
Node prev = jump(pos - 2);
prev.next = null;
tail = prev;
} else {
Node prev = jump(pos - 2);
removedItem = prev.next;
prev.next = prev.next.next;
}
count--;
return removedItem.data;
}
public int remove(T item) {
int numRemoved = 0;
int pos = -1;
try {
while ((pos = contains(item)) > 0) {
remove(pos);
numRemoved++;
}
} catch (ListException e){
System.out.print(e);
}
return numRemoved;
}
int find_length(Node list){
int count = 0;
while (list!=null) {
count++;
list=list.next;
}
return count;
}
public void replace(T item, int pos) throws ListException {
if (pos < 1 || pos > count + 1) {
throw new ListException("Invalid position to replace at");
}
Node list = this.getHead();
int length = find_length(list);
if(pos<1||pos>length){
return;
}
while(list!=null){
pos--;
if(pos==0){
list.data=item;
return;
}
list=list.next;
}
}
public T retrieve(int pos) throws ListException {
T item = null;
if (pos < 1 || pos > count) {
throw new ListException("Invalid position to retrieve from");
}
if (pos == 1) {
return head.data;
}
Node prev = jump(pos - 2);
item = prev.next.data;
return item;
}
public LinkedList<T> reverse() {
LinkedList<T> l = new LinkedList<T>();
try {
for (int pos = count; pos > 0; pos--)
l.add(retrieve(pos));
}
catch (ListException e) {
System.out.println("Should not occur (Reverse)");
}
return l;
}
public String toString() {
String temp = "";
Node nd = head;
while (nd != null) {
temp += nd.data + "-";
nd = nd.next;
}
return temp;
}
}
What I'm trying to get is the since the Node class is located in the same class as my LinkedList class, it is referred to as an internal class. If it were to be separate, would I have to implement a Node class similarly to the LinkedListInterface<T> class? What else would have to be coded differently?

I need help making a toString method that must pass certain tests, Java

I need help making this toString method pass the tests at the bottom. I am currently getting the error (expected:<0:20, 1:[1]0> but was <0:20, 1:[2]0>). addFirst is working 100%, but I'm not sure what is wrong here.
public class LList
{
public Node head;
private int i;
private int size;
public void addFirst(int value)
{
Node n = new Node();
n.value = value;
n.next = head;
head = n;
}
public void removeFirst()
{
if (head != null)
{
// commone case: there is at least one node
head = head.next;
}
else
{
// no nodes
throw new Banana();
}
}
public int size()
{
Node current = head;
int count = 0;
while(current != null)
{
count++; // keep count of nodes
current = current.next; // move to next node
}
return count;
}
public int get(int index)
{
int count = 0;
Node current = head;
if (index < 0 || index >= size())
{
throw new Banana();
}
while(count != index)
{
count++;
current = current.next;
}
return current.value;
}
public String toString()
{
String s = "";
Node current = head;
//current = head;
if (size() == 0)
{
return s;
}
else
{
s = s + "" + i + ":" + current.value;
for (int i = 1; i < size(); i++)
{
s = s + ", " + i + ":" + current.value;
}
return s;
}
}
public class Node
{
public int value;
public Node next;
}
#Test
public void testToString()
{
LList a = new LList();
assertEquals("", a.toString());
a.addFirst(10);
assertEquals("0:10", a.toString());
a.addFirst(20);
assertEquals("0:20, 1:10", a.toString());
a.addFirst(30);
assertEquals("0:30, 1:20, 2:10", a.toString());
}
You should iterate (walk over) all Nodes.
Use while loop for that, e.g.:
public String toString() {
String s = "";
Node current = head;
// current = head;
if (size() != 0) {
int i = 0;
s = s + "" + i + ":" + current.value;
while(current.next != null) {
i++;
current = current.next;
s = s + ", " + i + ":" + current.value;
}
}
return s;
}

Erorr with the nullpointer

public class List {
private class Node {
public Node next = null;
Object element;
Node text;
Node(Object element, Node prevNode) {
this.element = element;
prevNode = this;
}
Node(Object element) {
this.element = element;
element = null;
}
}
private Node head;
private Node tail;
private int count;
public List() {
this.head = null;
this.tail = null;
this.count = 0;
}
public void add(Object item) {
if (head == null) {
// We have empty list
head = new Node(item);
tail = head;
} else {
// We have non-empty list
Node newNode = new Node(item, tail);
tail = newNode;
}
count++;
}
public Object remove(int index) {
if (index >= count || index < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
// Find the element at the specified index
int currentIndex = 0;
Node currentNode = head;
Node prevNode = null;
while (currentIndex < index) {
prevNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
count--;
if (count == 0) {
head = null;
tail = null;
} else if (prevNode == null) {
head = currentNode.next;
} else {
prevNode.next = currentNode.next;
}
}
return currentNode.element;
}
public int remove(Object item) {
// Find the element containing searched item
int currentIndex = 0;
Node currentNode = head;
Node prevNode = null;
while (currentNode != null) {
if ((currentNode.element != null && currentNode.element
.equals(item))
|| (currentNode.element == null)
&& (item == null)) {
break;
}
prevNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
}
if (currentNode != null) {
// Element is found in the list. Remove it
count--;
if (count == 0) {
head = null;
tail = null;
} else if (prevNode == null) {
head = currentNode.next;
} else {
prevNode.next = currentNode.next;
}
return currentIndex;
} else {
// Element is not found in the list
return -1;
}
}
public int indexOf(Object item) {
int index = 0;
Node current = head;
while (current != null) {
if ((current.element != null && current.element.equals(item))
|| (current.element == null) && (item == null)) {
return index;
}
current = current.next;
index++;
}
return -1;
}
public boolean contains(Object item) {
int index = indexOf(item);
boolean found = (index != -1);
return found;
}
public Object elementAt(int index) {
if (index >= count || index < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
Node currentNode = this.head;
for (int i = 0; i < index; i++) {
currentNode = currentNode.next;
}
return currentNode.element;
}
public int getLength() {
return count;
}
public static void main(String[] args) throws NullPointerException {
List shoppingList = new List();
shoppingList.add("Milk");
shoppingList.add("Honey");
shoppingList.add("Olives");
shoppingList.add("Beer");
shoppingList.remove("Olives");
System.out.println("We need to buy:");
for (int i = 0; i < shoppingList.getLength(); i++) {
System.out.println(shoppingList.elementAt(i));
}
System.out.println("Do we have to buy Bread? "
+ shoppingList.contains("Bread"));
}
}
Its giving me that in maina and index of have nullpointer.
Where is my mistake ?
And i want to know how to fix this problem. Thank you.
I would be very grateful if you could give me some feedback for code.
You do not set next when you create your Nodes, so next is always null.
This
Node(final Object element, Node prevNode) {
this.element = element;
prevNode = this;
}
should be
Node(final Object element, Node prevNode) {
this.element = element;
prevNode.next = this;
}
I understand there's something in your code that's giving you nullpointerException when you run the program, but there's no need of it being in the main method, any method called by main may be giving the exception. Still, try this:
Replace this line:
for (int i=0; i<shoppingList.getLength(); i++) {
by this one:
for (int i=0; i < shoppingList.length(); i++) {
if .length() doesn't work, maybe .size() will do.
for (int i=0; i<shoppingList.size(); i++) {
If you are using eclipse, netbeans or any other environment, post which line is throwing the NullPointerException. We can't help you unless you give us more data.

How to delete the current node in a singly linked list?

I am trying to finish a program and I'm caught at a spot. My deleteCurrentNode method only partially works. For some reason when I try to traverse the linked list to find the currentNode it never finds it. Can someone provide me with a tip of how to get it to work?
The method itself checks 4 conditions:
If the list is empty.
If currentNode is null.
If the currentNode is the first node in the list.
If currentNode is somewhere in the list.
The other conditions work (to my knowledge). 4 is where the issue is.
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);
for(int i=0; i< dataTest.length(); i++) { test.last(); test.deleteCurrentNode(); }
System.out.println("[4] "+test);
for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); test.last(); }
System.out.println("[5] "+test);
while(!test.isEmpty()) { test.deleteFirstNode(); }
System.out.println("[6] "+test);
for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); test.last(); }
System.out.println("[7] "+test);
while(!test.isEmpty()) { test.deleteFirstNode(false); }
System.out.println("[8] "+test);
for(int i=0; i< dataTest.length(); i++) { test.insertBeforeCurrentNode(new String(new char[] { dataTest.charAt(i) })); test.first(); }
System.out.println("[9] "+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("current " + getCurrent());
//System.out.println("pointer " + getListPtr());
}
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()
{
//System.out.println("in delete current");
Object nData;
Node previous;
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} //if list is empty throw exception
checkCurrent(); //check if currentNode is null, method throws exception if it is.
nData = getCurrent().getData();
if (getCurrent() == getListPtr())
{
setListPtr(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount -1;
}
else
{
previous = getListPtr();
while (previous.getNext() != getCurrent())
{
previous = previous.getNext();
//System.out.println("test"+ previous);
}
if (getCurrent().getNext() != null)
{
previous.setNext(null);
}
previous.setNext(getCurrent().getNext()); }
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 = getListPtr();
//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 = getListPtr();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
}
}
[4] should read the same as [2] (List contains 0 nodes.)
Note: Cannot use any more variables/methods/etc that I already have. And I cannot use head nodes.
if you have a Node class, representing one node of the list like:
public class Node{
public Object value;
public Node next;
public Node(){
}
public Node(Object p){
value= p;
}
public String toString(){
return "" + this.value.toString();
}
}
Than you in your List implementation (let's say MyList) you will have (methods only for removing):
public class MyList{
private Node head;
public Object removeFirst(){
if(head == null){
return null;
}
Object o= head.value;
head= head.next;
return o;
}
// remove by index
public Object remove(int i){
int n= this.size();
if(i<0 || i>=n){
return null;
}
if(i==0){
return this.removeFirst();
}
int k=0;
Node t= head;
while(k < i-1){
t= t.next;
k= k+1;
}
Object o= t.next.value;
t.next= t.next.next;
return o;
}
//remove by object
public boolean remove(Object o){
int k= this.indexOf(o);
if(k<0){
return false;
}
this.remove(k);
return true;
}
//not necessary, but you may study the logic
public Object removeLast(){
Object o= null;
if(head!=null){
if(head.next==null){
o= head.value;
head= null;
}else{
Node t= head.next;
while(t.next.next != null){
t= t.next;
}
o= t.next.value;
t.next= null;
}
}
return o;
}
}
Edit: you have some problems when your array is only containing 1 element.
For example in your last() method ->
while (!atEnd()) {
setCurrent(getCurrent().getNext());
}
You might want to consider guarding against null in your code. It's best not to make assumptions.
For instance,
public boolean atEnd()
{
return getCurrent().getNext() == null;
}
might be better written as
public boolean atEnd()
{
if (getCurrent() != null)
{
return getCurrent().getNext() == null;
}
return true;
}
This isn't necessarily the best way to do it; you might want to throw a NoCurrentNodeException or something. It depends on the semantics you're looking for.
Either way, you won't get buried in NullPointerExceptions.
public class LinkedList
{
private Node currentNode;
private Node firstNode;
private int nodeCount;
public static void main(String[] args)
{
String data;
Object hold;
LinkedList list;
data = "abcdefghijklmnopqrstuvwxyz";
hold = null;
list = new LinkedList();
for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); }
System.out.println("[1] "+list);
for(int i=0; i< data.length(); i++) { list.deleteCurrentNode(); }
System.out.println("[2] "+list);
for(int i=0; i< data.length(); i++)
{
list.insertBeforeCurrentNode(new String(new char[] { data.charAt(i) }));
if(i%2 == 0) { list.first(); } else { list.last(); }
}
System.out.println("[3] "+list);
for(int i=0; i< data.length(); i++) { list.last(); list.deleteCurrentNode(); }
System.out.println("[4] "+list);
for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); list.last(); }
System.out.println("[5] "+list);
while(!list.isEmpty()) { list.deleteFirstNode(); }
System.out.println("[6] "+list);
for(int i=0; i< data.length(); i++) { list.insert(new String(new char[] { data.charAt(i) })); list.last(); }
System.out.println("[7] "+list);
while(!list.isEmpty()) { list.deleteFirstNode(false); }
System.out.println("[8] "+list);
for(int i=0; i< data.length(); i++) { list.insertBeforeCurrentNode(new String(new char[] { data.charAt(i) })); list.first(); }
System.out.println("[9] "+list);
list.first();
list.next();
list.deleteFirstNode(true);
list.deleteCurrentNode();
for(int i=0; i< 5; i++) { hold = list.getData(); list.next(); }
for(int i=0; i< 10; i++) { list.next(); }
list.insertAfterCurrentNode(hold);
list.first();
list.next();
hold = list.getData();
list.deleteCurrentNode();
for(int i=0; i<9; i++) {list.deleteCurrentNode(); list.last(); }
list.insert(hold);
list.first();
list.next();
list.next();
list.next();
list.deleteFirstNode(false);
hold = list.getData();
list.deleteCurrentNode();
list.last();
list.insertAfterCurrentNode(hold);
list.deleteFirstNode();
list.deleteFirstNode();
hold = list.getData();
list.deleteFirstNode();
list.last();
list.insertBeforeCurrentNode(hold);
list.first();
for(int i=0; i<6; i++) { list.next(); }
hold = list.getData();
list.deleteCurrentNode();
list.last();
list.insertBeforeCurrentNode(hold);
list.first();
list.deleteCurrentNode();
list.deleteCurrentNode();
hold = list.getData();
list.deleteCurrentNode();
for (int i=0; i< 7; i++) { list.next(); }
list.insertBeforeCurrentNode(hold);
for (int i=0; i< 4; i++) { list.first(); list.deleteCurrentNode(); }
System.out.println("\n\n"+list);
}
public LinkedList()
{
setListPtr(null);
setCurrent(null);
nodeCount = 0;
}
public boolean atEnd()
{
if (getCurrent() != null)
{
return getCurrent().getNext() == null;
}
return true;
}
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("current " + getCurrent());
//System.out.println("pointer " + getListPtr());
}
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()
{
//System.out.println("in delete current");
Object nData;
Node previous;
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");} //if list is empty throw exception
checkCurrent(); //check if currentNode is null, method throws exception if it is.
nData = getCurrent().getData();
if (getCurrent() == getListPtr())
{
setListPtr(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount -1;
}
else
{
previous = getListPtr();
//System.out.println(getCurrent());
//System.out.println(previous + "ptrb ");
while (previous.getNext() != getCurrent())
{
previous = previous.getNext();
//System.out.println("test"+ previous);
}
//System.out.println(previous.getNext() == getCurrent());
if (previous.getNext() == getCurrent())
{
//System.out.println("say hi");
previous.setNext(getCurrent().getNext());
deAllocateNode(getCurrent());
setCurrent(previous);
nodeCount = nodeCount - 1;
}
previous.setNext(getCurrent().getNext());
}
return nData;
}
public Object deleteFirstNode(boolean toDelete)
{
if (toDelete)
{
setCurrent(getListPtr().getNext());
}
deAllocateNode(getListPtr());
setListPtr(getListPtr().getNext());
nodeCount = nodeCount - 1;
return getListPtr();
}
public Object deleteFirstNode()
{
Object deleteFirst;
deleteFirst = deleteFirstNode(true);
//System.out.println("called");
return deleteFirst;
}
public int size()
{
return this.nodeCount;
}
public String toString()
{
String nodeString;
Node sNode;
sNode = getListPtr();
//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 = getListPtr();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
}
}
Thanks so much everyone for your contributions. They've helped me solve my problem (although somewhat obscurely.)
I'm answering my own question so that if anyone else happens to have a similar problem, they can use it as a tool of reference.
Once again, thanks.

How to sort a Linked list

I created a linked list using nodes that prints out a list(string) of names. I'm trying to write a sort method that prints out the names in alphabetical order. If this was integers it would be easy but I have no idea how to go about doing this. Any help or tips are appreciated.
-I cannot use the builtin collections.sort(). I need to make my own method.
SortMethod: (this is what I used when I was printing a list of numbers out but now its strings so I know I can't use the > operator. I just don't know how to replace it.
public void Sort( BigNode front)
{
BigNode first,second,temp;
first= front;
while(first!=null) {
second = first.next;
while(second!=null) {
if(first.dataitems < second.dataitems)
{
temp = new BigNode();
temp.dataitems =first.dataitems;
first.dataitems = second.dataitems;
second.dataitems = temp.dataitems;
}
second=second.next;
}
Heres the rest of program(I dont think its needed but just in case)
import java.util.*;
public class BigNode {
public String dataitems;
public BigNode next;
BigNode front ;
BigNode current;
String a = "1", b = "2", c = "3", d = "4";
String[] listlength;
public void initList(){
front = null;
}
public BigNode makeNode(String number){
BigNode newNode;
newNode = new BigNode();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(BigNode front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public BigNode findTail(BigNode front) {
BigNode current;
current = front;
while(current.next != null){
//System.out.print(current.dataitems);
current = current.next;
} //System.out.println(current.dataitems);
return current;
}
public void addNode(BigNode front ,String name){
BigNode tail;
if(isListEmpty(front)){
this.front = makeNode(name);
}
else {
tail = findTail(front);
tail.next = makeNode(name);
}
}
public void addAfter(BigNode n, String dataItem2) { // n might need to be front
BigNode temp, newNode;
temp = n.next;
newNode = makeNode(dataItem2);
n.next = newNode;
newNode.next = temp;
}
public void findNode(BigNode front, String value) {
boolean found , searching;
BigNode curr;
curr = front;
found = false;
searching = true;
while ((!found) && (searching)) {
if (curr == null) {
searching = false;
}
else if (curr.dataitems == value) { // Not sure if dataitems should be there (.data in notes)
found = true;
}
else {
curr = curr.next;
}
}
System.out.println(curr.dataitems);
}
public void deleteNode(BigNode front, String value) {
BigNode curr, previous = null; boolean found;
if (!isListEmpty(front)){
curr = front;
found = false;
while ((curr.next != null) && (!found)) {
if(curr.dataitems.equals(value)) {
found = true;
}
else {
previous = curr;
curr = curr.next;
}
}
if (!found) {
if(curr.dataitems.equals(value)) {
found = true;
}
}
if (found) {
if (curr.dataitems.equals(front.dataitems)){ // front.dataitems may be wrong .dataitems
front = curr.next;
} else {
previous.next = curr.next;
}
} else {
System.out.println("Node not found!");
//curr.next = null; // Not sure If this is needed
}
}
showList(front);
}
public void printNodes(String[] len){
listlength = len;
int j;
for (j = 0; j < len.length; j++){
addNode(front, len[j]);
} showList(front);
}
public void showList(BigNode front){
current = front;
while ( current.next != null){
System.out.print(current.dataitems + ", ");
current = current.next;
}
System.out.println(current.dataitems);
MenuOptions();
}
public void MenuOptions() {
Scanner in = new Scanner(System.in);
System.out.println("Choose an Option Below:");
System.out.println(a + "(Display Length of List)" + ", " + b + "(Delete a person)" + ", " + c + ("(Exit)"));
String pick = in.nextLine();
if (pick.equals(b)) {
System.out.println("Who would you like to delete?");
String delete = in.nextLine();
deleteNode(front, delete);
}
if (pick.equals(a)) {
System.out.println("Length of List = " + listlength.length);
MenuOptions();
}
if (pick.equals(c)) {
}
}
public static void main(String[] args) {
String[] names = {"Billy Joe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
x.printNodes(names);
}
}
first.dataitems.compareTo(second.dataitems)<0
or if you have a comparator
comp.compare(first.dataitems, second.dataitems)<0

Categories