class StackNode{
int data;
StackNode next;
public StackNode(int data, StackNode next){
this.data = data;
this.next = next;
}
}
public class StackWithLinkedList {
StackNode root = null;
public void push(int data){
if(root == null)
root = new StackNode(data, null);
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
temp.next = new StackNode(data, null);
}
}
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
int data = temp.data;
temp = null;
return data;
}
}
public void print(){
StackNode temp = root;
while(temp!= null){
System.out.print(temp.data +" ");
temp = temp.next;
}
System.out.print("\n");
}
public static void main(String[] args) {
StackWithLinkedList stack = new StackWithLinkedList();
for(int i = 1; i<=15; i++){
Random randomGen = new Random();
stack.push(randomGen.nextInt(i));
}
stack.print();
System.out.print("\n");
try {
System.out.println("Deleted: "+stack.pop());
System.out.println("Deleted: "+stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
stack.print();
}
}
I am trying to implement Stack with Linkedlist. In pop function i am traversing till the last node and making it null. When i print the list. it remain unchanged. Does assigning root to temp and traversing with it cause any problem?
You can avoid this all together by simplifying your implementation. It's just a stack so it's LIFO. All you need to do is make the last element push-ed the root. When pop-ing return the data in root and set root to the next in line.
The way you're doing it increases the typical complexity of O(1) to O(N) for the push and pop operations.
Something like:
public void push(int data) {
root = new StackNode(data, root);
}
public int pop() throws Exception {
if (root == null)
throw new Exception("No Elements in Stack");
else {
int data = root.data;
root = root.next;
return data;
}
}
As mentioned in other answer by #ChiefTwoPencils, that must be the preferred way of implementing this. However, to correct your logic of pop operation you shall keep track of second last item and once you get that you can return data value of next node and set the next link to null.
Here is changed logic from your code of pop method
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
int data = -1;
if(root.next==null) {
data = root.data;
root = null;
return data;
}
StackNode temp = root;
while(temp.next.next != null)
temp = temp.next;
data = temp.next.data;
temp.next = null;
return data;
}
}
Hope it helps.
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
StackNode temp = root;
StackNode prev;
while(temp.next != null){
prev = temp;
temp = temp.next;
}
int data = temp.data;
prev.next = null;
return data;
}
}
Related
The code is working fine when I try to delete any element for some indices but for some others it is not working. For example, Whenever I try to delete by passing delete(1) it may work and if I try with delete(2) it may show NullPointerException. Here is the code :
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
n = n.next;
}
n.prev.next = n.next;
n.next.prev = n.prev;
}
}
So this is my code and You can see the delete method over there. I even run through debug mode, it is showing error at n.prev.next = n.next
Any kind of help is highly appreciated.
When I ran your code, the NullPointerException occurred on this line:
n.next.prev = n.prev;
and not on the line you said in your question.
The NullPointerException occurs when you delete the last Node in the list. This is because the value of next for the last Node in the list is null. So n.next is null and therefore n.next.prev throws NullPointerException.
You need to check whether n.next is null and only if it isn't you can execute the code: n.next.prev = n.prev.
Also, you need to check the value of parameter index in method delete(). One way would be to keep track of the number of elements in the list.
The below code incorporates the changes described. The parts I added are preceded by the comment Change here
public class DbLnkLst {
private static class Node {
int data;
Node next;
Node prev;
}
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
// Change here.
if (index < 0) {
throw new IllegalArgumentException("negative index: " + index);
}
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
// Change here.
if (n.next == null) {
throw new IllegalArgumentException("invalid index: " + index);
}
n = n.next;
}
n.prev.next = n.next;
// Change here.
if (n.next != null) {
n.next.prev = n.prev;
}
}
/**
* For testing the class.
*/
public static void main(String[] args) {
DbLnkLst list = new DbLnkLst();
list.insert(0);
list.insert(1);
list.insert(2);
System.out.println("List is:");
list.show();
list.delete(2);
System.out.println("After 'delete(2)', list is:");
list.show();
System.out.println("Try 'delete(2)' again.");
list.delete(2);
}
}
The output from running the above code is below:
List is:
0
1
2
After 'delete(2)', list is:
0
1
Try 'delete(2)' again.
Exception in thread "main" java.lang.IllegalArgumentException: invalid index: 2
at genrlprj/misctsts.DbLnkLst.delete(DbLnkLst.java:73)
at genrlprj/misctsts.DbLnkLst.main(DbLnkLst.java:100)
I had written my own Linked Class Codes with Node first and last, since there exists a Node last, I encountered problems regarding reference and pointer manipulations when I tried to manually created the LinkedList in the main method and test it.
I am quite familiar with the recursion implemented in the "addFirst" "addLast" and "remove" methods, but now somehow the reference to the Node first becomes null after addFirst Method.
public class LinkedList<T> {
Node first,last,temp;
public class Node{
T value;
Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public String toString(){
if(next == null){
return value.toString();
}
else{
return value.toString() + " " + next.toString();
}
}
public T getLL(int index){
if(index == 0){
return value;
}
if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
return next.getLL(index-1);
}
public T removeLL(int x){
if(x == 1){
T value = next.value;
next = next.next;
return value;
}
else if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
else{
return next.removeLL(x-1);
}
}
}
public LinkedList(T value) {
temp = new Node(value,null);
first = new Node(value,null);
last = temp;
}
public static void main(String[] args) {
/**
* [120,110,100,90,80];
*/
LinkedList L = new LinkedList(100);
L.addFirst(110);
L.addFirst(120);
L.addLast(90);
L.addLast(80);
System.out.println(L.size());
System.out.println(L.remove(0));
System.out.println(L.last.toString());
//return null which causes the remove method not to work.
System.out.println(L.first);
}
public void addFirst(T value){
first = new Node(value,first);
}
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
last.next = new Node(value,null);
last = new Node(value,null);
}
public T get(int index){
if(first == null){
throw new IndexOutOfBoundsException("empty list");
}
return first.getLL(index);
}
public int size(){
int c = 0;
while(first != null){
first = first.next;
c++;
}
return c;
}
public T remove(int x){
if(first == null){
throw new IndexOutOfBoundsException("Tried to remove from empty list");
}
if (x == 0) {
T value = first.value;
first = first.next;
return value;
}
return first.removeLL(x);
}
}
I expected that the Node first pointed to the first element of the LinkedList instead of pointing to null. Meanwhile, this won't affect the pointer of Node last.
Looks like the problem inside the AddLast function. You braking the list.
Shouldn't it be like this?
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
p.next = new Node(value,null);
last = p.next;
//last = new Node(value,null);
}
Update Regarding your comment and updated answer.
Your size function is wrong:
public int size(){
int c = 0;
while(first != null){
first = first.next; // <-- now first point to the last and length is 1
c++;
}
return c;
}
When you remove the first element first is null. You have to create temporary variable to traverse your list. To check this comment the line where you calculate size.
Your are actually not quite right last.next = new Node(value,null); point to the new node. But instead of connecting again last = last.next your new node is gone because you create your new node for the last but last.next pointed to new node and hence last is not last anymore. (I think your understood what I meant)
I was doing this exercice:
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. Example input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
I found it hard to find a solution for Singly linked list (that created by my own, not using library), I would like to know if there is uncessary code blocks in my code and is there a way to avoid putting in two lists and then merge? because it seems to have very slow performance like that.
public CustomLinkedList partition(CustomLinkedList list, int x) {
CustomLinkedList beforeL = new CustomLinkedList();
CustomLinkedList afterL = new CustomLinkedList();
LinkedListNode current = list.getHead();
while (current != null) {
if (current.getData() < x) {
addToLinkedList(beforeL, current.getData());
} else {
addToLinkedList(afterL, current.getData());
}
// increment current
current = current.getNext();
}
if (beforeL.getHead() == null)
return afterL;
mergeLinkedLists(beforeL, afterL);
return beforeL;
}
public void addToLinkedList(CustomLinkedList list, int value) {
LinkedListNode newEnd = new LinkedListNode(value);
LinkedListNode cur = list.getHead();
if (cur == null)
list.setHead(newEnd);
else {
while (cur.getNext() != null) {
cur = cur.getNext();
}
cur.setNext(newEnd);
cur = newEnd;
}
}
public void mergeLinkedLists(CustomLinkedList list1, CustomLinkedList list2) {
LinkedListNode start = list1.getHead();
LinkedListNode prev = null;
while (start != null) {
prev = start;
start = start.getNext();
}
prev.setNext(list2.getHead());
}
CustumLinkedList contains two attributes: -LinkedListNode which is the head and an int which is the size.
LinkedListNode contains two attributes: One of type LinkedListNode pointing to next node and one of type int: data value
Thank you.
The problem of your code is not merging two lists as you mentioned. It's wrong to use the word merge here because you're only linking up the tail of the left list with head of right list which is a constant time operation.
The real problem is - on inserting a new element on the left or right list, you are iterating from head to tail every time which yields in-total O(n^2) operation and is definitely slow.
Here I've wrote a simpler version and avoid iterating every time from head to insert a new item by keeping track of the current tail.
The code is very simple and is definitely faster than yours(O(n)). Let me know if you need explanation on any part.
// I don't know how your CustomLinkedList is implemented. Here I wrote a simple LinkedList node
public class ListNode {
private int val;
private ListNode next;
public ListNode(int x) {
val = x;
}
public int getValue() {
return this.val;
}
public ListNode getNext() {
return this.next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
ListNode left = null;
ListNode right = null;
ListNode iterL = left;
ListNode iterR = right;
while(iter != null) {
if(iter.getValue() < x) {
iterL = addNode(iterL, iter.getValue());
}
else {
iterR = addNode(iterR, iter.getValue());
}
iter = iter.getNext();
}
// link up the left and right list
iterL.setNext(iterR);
return left;
}
public ListNode addNode(ListNode curr, int value) {
ListNode* newNode = new ListNode(value);
if(curr == null) {
curr = newNode;
} else {
curr.setNext(newNode);
curr = curr.getNext();
}
return curr;
}
Hope it helps!
If you have any list of data, access orderByX Method.
Hope it would help you.
public class OrderByX {
Nodes root = null;
OrderByX() {
root = null;
}
void create(int[] array, int k) {
for (int i = 0; i < array.length; ++i) {
root = insert(root, array[i]);
}
}
Nodes insert(Nodes root, int data) {
if (root == null) {
root = new Nodes(data);
} else {
Nodes tempNew = new Nodes(data);
tempNew.setNext(root);
root = tempNew;
}
return root;
}
void display() {
Nodes tempNode = root;
while (tempNode != null) {
System.out.print(tempNode.getData() + ", ");
tempNode = tempNode.getNext();
}
}
void displayOrder(Nodes root) {
if (root == null) {
return;
} else {
displayOrder(root.getNext());
System.out.print(root.getData() + ", ");
}
}
Nodes orderByX(Nodes root, int x) {
Nodes resultNode = null;
Nodes lessNode = null;
Nodes greatNode = null;
Nodes midNode = null;
while (root != null) {
if (root.getData() < x) {
if (lessNode == null) {
lessNode = root;
root = root.getNext();
lessNode.setNext(null);
} else {
Nodes temp = root.getNext();
root.setNext(lessNode);
lessNode = root;
root = temp;
}
} else if (root.getData() > x) {
if (greatNode == null) {
greatNode = root;
root = root.getNext();
greatNode.setNext(null);
} else {
Nodes temp = root.getNext();
root.setNext(greatNode);
greatNode = root;
root = temp;
}
} else {
if (midNode == null) {
midNode = root;
root = root.getNext();
midNode.setNext(null);
} else {
Nodes temp = root.getNext();
root.setNext(midNode);
midNode = root;
root = temp;
}
}
}
resultNode = lessNode;
while (lessNode.getNext() != null) {
lessNode = lessNode.getNext();
}
lessNode.setNext(midNode);
while (midNode.getNext() != null) {
midNode = midNode.getNext();
}
midNode.setNext(greatNode);
return resultNode;
}
public static void main(String... args) {
int[] array = { 7, 1, 6, 2, 8 };
OrderByX obj = new OrderByX();
obj.create(array, 0);
obj.display();
System.out.println();
obj.displayOrder(obj.root);
System.out.println();
obj.root = obj.orderByX(obj.root, 2);
obj.display();
}
}
class Nodes {
private int data;
private Nodes next;
Nodes(int data) {
this.data = data;
this.next = null;
}
public Nodes getNext() {
return next;
}
public void setNext(Nodes next) {
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
I think that maintaining two lists is not an issue. It is possible to use a single list, but at the cost of loosing some of the simplicity.
The principal problem seems to be the addToLinkedList(CustomLinkedList list, int value) method.
It iterates throughout the entire list in order to add a new element.
One alternative is to always add elements at the front of the list. This would also produce a valid solution, and would run faster.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to understand how Linked List data structures works, but in the past week after researching it and watching tutorials, I'm still confused. I'm trying to delete a node, when a node is not the head or the tail.
I'm working with a doubly linked list
My Linked List: [A]=[B]=[C]=[D]=[E]=[F]
I'm trying to delete Node B
This is my delete method
public GNode deleteNode(E e) {
GNode temp = new GNode(e); // This gets Node: [B]
GNode tempNext = temp.getNext(); // This gets Node: [C]
GNode tempPrevious = temp.getPrevious(); // This get Node: [A]
GNode current = findNode(temp, e); // This finds Node: [B]
// Deletes Head
if (this.head.getData().equals(e)) {
head = head.next;
head.previous = null;
this.size--;
}
// Delete Tail
if (this.tail.getData().equals(e)) {
tail = tail.previous;
tail.next = null;
this.size--;
}
// Delete Node
else {
if(findNode(temp,e) == e){
System.out.println("VALUE: " + temp.next);// Using this to debug. BUT temp.next returns null !?
tempPrevious.setNext(tempNext);
tempNext.setPrevious(tempPrevious);
size--;
}
}
return temp;
}
By doing some debugging I think I may not be initializing my variables correctly or looping through the list. Would anybody be able to point me to the right direction? And see what I may be doing wrong?
This is the entire code I'm working with
import java.io.*;
import java.util.*;
public class GDList<E> implements Cloneable {
private static class GNode<E> {
private E data;
private GNode<E> previous;
private GNode<E> next;
public GNode(E e) {
data = e;
previous = null;
next = null;
}
public E getData() {
return data;
}
public GNode getPrevious() {
return previous;
}
public GNode getNext() {
return next;
}
public void setData(E e) {
data = e;
}
public void setPrevious(GNode p) {
previous = p;
}
public void setNext(GNode p) {
next = p;
}
public Iterator<String> iterator() {
// TODO Auto-generated method stub
return null;
}
}
private GNode<E> head;
private GNode<E> tail;
private int size; // number of nodes in a list
public GDList() {
head = null;
tail = null;
size = 0;
}
public int addToHead(E e) {
GNode temp = new GNode(e);
if (head == null) {
head = temp;
tail = temp;
} else {
if (findNode(head, e) == null) {
temp.setNext(head);
head.setPrevious(temp);
head = temp;
} else
return 1;
}
size++;
return 0;
}
public int addToTail(E e) {
GNode temp = new GNode(e);
if (head == null) {
head = temp;
tail = temp;
} else {
if (findNode(head, e) == null) {
temp.setPrevious(tail);
tail.setNext(temp);
tail = temp;
} else
return 1;
}
size++;
return 0;
}
public int addAfter(GNode n, E e) {
if (n == null)
throw new IllegalArgumentException("The node n cannot be null");
if (findNode(head, e) != null)
return 1;
if (n == tail) {
addToTail(e);
} else {
GNode temp = new GNode(e); // element
GNode tempNext = n.getNext(); // location of element
temp.setNext(tempNext); // set element to the next location where
// the position is null
tempNext.setPrevious(temp); //
temp.setPrevious(n);
n.setNext(temp);
size++;
}
return 0;
}
public int addBefore(GNode n, E e) {
if (n == null)
throw new IllegalArgumentException("The node n c6annot be null");
if (findNode(head, e) != null)
return 1;
if (n == head)
addToHead(e);
else {
GNode temp = new GNode(e);
GNode tempPrevious = n.getPrevious();
temp.setNext(n);
n.setPrevious(temp);
tempPrevious.setNext(temp);
temp.setPrevious(tempPrevious);
size++;
}
return 0;
}
#SuppressWarnings("unchecked")
public GNode deleteNode(E e) {
// Linked List [22]=[3]=[17]=[9]
GNode prevNode = this.head;
GNode temp = new GNode(e); // Node: [17]
GNode tempNext = temp.getNext(); // Node: [9]
GNode tempPrevious = temp.getPrevious(); // Node: [3]
GNode current = findNode(temp, e); // Node: [17]
// Deletes Head
if (this.head.getData().equals(e)) {
head = head.next;
head.previous = null;
this.size--;
}
// Delete Tail
if (this.tail.getData().equals(e)) {
tail = tail.previous;
tail.next = null;
this.size--;
}
else {
if(findNode(temp,e) == e){
System.out.println("VALUE: " + temp.next);// Using this to debug. BUT temp.next returns null !?
tempPrevious.setNext(tempNext);
tempNext.setPrevious(tempPrevious);
size--;
}
}
return temp;
}
public GNode deleteAfter(E e) {
GNode temp = findNode(head, e);
if (temp == tail || temp == null)
return null;
return (deleteNode((E) temp.getNext().data));
}
public GNode deleteBefore(E e) {
GNode temp = findNode(head, e);
if (temp == head || temp == null)
return null;
return (deleteNode((E) temp.getPrevious().data));
}
public GNode findNode(GNode p, E e) {
GNode current = p; // current is the cursor
while (current != null && current.data != e) // while is not what I'm
// looking for
current = current.getNext();
return current;
}
public void printList() {
System.out.print("Number of nodes = " + size + ", List is: ");
if (head != null) {
GNode current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.getNext();
}
} else {
System.out.println("The list is empty");
}
System.out.println();
}
public static void main(String[] args) throws Exception {
GDList<String> names = new GDList<String>();
names.printList();
names.addToTail("A");
names.addToTail("B");
names.addToTail("C");
names.addToTail("D");
names.addToTail("E");
names.addToTail("F");
System.out.println();
// Delete Node
System.out.println();
System.out.println("\nDelete Node");
names.printList();
names.deleteNode("B"); // Delete B
names.printList();
}
}
When you create a new object GNode temp = new GNode(e);, temp.next and temp.previous is set to null. You can look at the constructor here.
public GNode(E e) {
data = e;
previous = null;
next = null;
}
You already have a method called findNode which is gonna simplify a lot of it.
public GNode deleteNode(E e) {
GNode current = findNode(head, e); // This finds Node: [B]
// a node with data e doesn't exist
if (current == null) {
return null;
}
// get the next and previous node
GNode previous = current.previous;
GNode next = current.next;
// current node is head
if (previous == null) {
this.head = current.next;
this.head.previous = null;
}
// current node is tail
if (next == null) {
this.tail = current.previous;
this.tail.next = null;
}
if (previous != null || next != null) {
GNode temp = current.previous;
temp.next = current.next;
temp = current.next;
temp.previous = current.previous;
}
return current;
}
I have a project where I have to write a bunch of sort methods and measure the time complexity for each, and output the results to an output text file. the program runs but i get some null pointer exceptions in bubblesort method. here is my code and error, if you can tell me how to fix my sort methods, that would be awesome!
linked list class:
public class LinkedList {
protected static class Node {
Comparable item;
Node prev, next;
public Node(Comparable newItem, Node prev, Node next) {
this.item = newItem;
this.prev = prev;
this.next = next;
}
public Node (Comparable newItem) {
this(newItem, null, null);
}
public Node() {
this(null, null, null);
}
public String toString() {
return String.valueOf(item);
}
}
private Node head;
private int size;
public int dataCompares, dataAssigns;
public int loopCompares, loopAssigns;
public int other;
public LinkedList() {
head = new Node(null, null, null);
head.prev = head;
head.next = head;
size = 0;
}
public boolean add(Comparable newItem) {
Node newNode = new Node(newItem);
Node curr;
if(isEmpty()) {
head.next = newNode;
head.prev = newNode;
newNode.next = head;
newNode.prev = head;
} else {
newNode.next = head;
newNode.prev = head.prev;
head.prev.next = newNode;
head.prev = newNode;
}
size++;
return false;
}
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head;
while(curr!=null) {
if(curr.item.compareTo(item)==0) {
if(prev==null) {
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
public void removeAll() {
this.head.prev = null;
this.head.next = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean remove(Object item) {
return true;
}
public void insertSortNode() {
Node back = head;
if (size < 2)
return;
back = back.next; // SECOND entry in the list
while ( back != null ) { // I.e., end-of-list
Comparable value = back.item;
Node curr = head; // Start at the front
// Find insertion point for value;
while (curr != back && value.compareTo(curr.item) >= 0)
curr = curr.next;
// Propogate values upward, inserting the value from back
while (curr != back){
Comparable hold = curr.item;
curr.item = value;
value = hold;
curr = curr.next;
}
back.item = value; // Drop final value into place!
back = back.next; // Move sorted boundary up
}
} // end insertSort()
public void selSort() {
Node front = head;
// Nothing to do on an empty list
if ( front == null )
return;
while ( front.next != null ) { // skips a one-entry list
Node tiny = front;
Node curr = front.next;
Comparable temp = front.item; // start the swap
for ( ; curr != null ; curr = curr.next ) {
if ( tiny.item.compareTo(curr.item) > 0 )
tiny = curr;
}
front.item = tiny.item; // Finish the swap
tiny.item = temp;
front = front.next; // Advance to the next node
}
// The structure is unchanged, so the validity of tail is unchanged.
}
public void bubbleSort() {
Node Trav=head.next;
Node Trail=head.next;
Comparable temp;
if (Trav != null)
Trav = Trav.next;
while(Trav!=null) {
if (Trav.item.compareTo(Trail.item)<0) {
temp = Trail.item;
Trail.item=Trav.item;
Trav.item = temp;
}
Trail=Trav;
Trav=Trav.next;
}
}
public void insertSortArray() {
Node insert1, cur, tmp1;
Comparable temp;
for(insert1 = this.head.next.next; insert1!=this.head; insert1 = insert1.next) {
//++loopcompares; ++loopassigns;
for (cur = head.next; cur!=insert1; cur=cur.next) {
//++loopCompares; ++loopassigns;
//++datacompares;
if(insert1.item.compareTo(cur.item)<0) {
temp=insert1.item;
//++dataassign
tmp1=insert1;
//++other
while(tmp1!=cur.prev) {
//++loopcomares
tmp1.item=tmp1.prev.item;
tmp1=tmp1.prev;
//++dataassign+=2
}
//++loopcompares
cur.item = temp;
//++dataassign;
break;
}
}
//++loopcompares; ++loopassigns;
}
//++loopcompares; ++loopassigns
}
public void disp6sortsFile(boolean disp, String fileName, String header, String data) {
FileWriter fw = null;
PrintWriter pw = null;
try {
File file = new File(fileName);
fw = new FileWriter(file, true);
pw = new PrintWriter(fw, true);
} catch (IOException e) {
System.err.println("File open failed for " +fileName+ "\n" + e);
System.exit(-1);
}
if (disp) {
pw.print(header + "\n");
}
pw.print(data + "\n");
pw.close();
}
}
here is my error:
Exception in thread "main" java.lang.NullPointerException
at LinkedList.bubbleSort(LinkedList.java:149)
at LinkListTester.main(LinkListTester.java:51)
the linkedlisttester error is simply list1.bubbleSort(); so bubble sort is the problem.
Change:
public String toString() {
return this.item.toString();
}
to:
public String toString() {
return String.valueOf(item); // Handle null too.
}
For add return true. Might check that item is not null if so desired.
remove is written for a single linked list.
In remove the head has a null item, which might have caused the error. Also as we have a circular list with a dummy node for head, the termination should not test for null but head. Otherwise a not present item will loop infinitely.
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head.next; // !
while(curr!=head) { // !
if(curr.item.compareTo(item)==0) {
if(prev==null) { // ! WRONG, but I will not correct home work ;)
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
swap is written for a single linked list.
And here I stopped reading, as I've come to the usages.
Second Edit:
All algorithmic functions, i.e. bubbleSort, have the following control flow:
while(Trav!=null) { ... Trav = Trav.next; }
But the data structure is defined cyclic, so eventually you arrive back at head and there the item is null.
The solution is to have for the first Node a prev null, and for the last Node a next null.
To make this clear, readable, you could substitute the Node head with:
Node first;
Node last;