For the below code, I would like to know why the size of the linked list keeps giving me a null pointer exeption and why my pushEnd method to push a new node at the end doesnt work, it add an element after a few nodes and gets rid of rest.
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
/* Inserts a new Node at front of the list. */
public Node push(int data)
{
Node newNode = new Node(data);
newNode.next = head;
return head = newNode;
}
public Node pushEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
newNode.next = null;
while(head != null) {
head = head.next;
head.next = newNode;
return newNode;
}
return head;
}
public int getSize() {
int size = 0;
while(this.head != null) {
size++;
head = head.next;
}
return size;
}
public void printList() {
while (this.head !=null) {
System.out.print(head.data + "-->");
head = head.next;
}
System.out.println(head);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.push(35);
ll.push(100);
ll.push(14);
ll.push(44);
ll.push(10);
ll.push(8);
System.out.println("Created Linked list is:");
ll.printList();
System.out.println(ll.getSize());
}
}
I want to figure out the size of the linked list and be able to add nodes at the end.
Your while loops modify the head variable directly. This causes your other code to fail because now head is pointing to the last node in the list.
Create a new local variable for use in the while loops (instead of modifying head directly). That should fix it!
You are changing head reference, due to which you are getting incorrect output. You should make temp refer to head, do your operation using temp which will not affect head. It should be like below:
public class LinkedList {
Node head;
/* Inserts a new Node at front of the list. */
public void push(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void pushEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
newNode.next = null;
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
public int getSize() {
int size = 0;
Node temp = head;
while (temp != null) {
size++;
temp = temp.next;
}
return size;
}
public void printList() {
Node temp = this.head;
while (temp != null) {
System.out.print(temp.data + "-->");
temp = temp.next;
}
System.out.println(temp);
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
I am having a little bit of difficulties with the Recursive concept.
Given a LinkedList with Integer values
L1 = (2->1->4->6->3)
L2= (1->9->6->3)
The function should remove the Odd numbers from the linkedlist starting at the integer N and returns a reference to the new head
i.e
L1.deleteOdd(2) = > (2->4->6)
L2.deleteOdd(1) = > (6)
I implemented a normal iterative function that does the job, here it is
public node deleteOdd(int n) {
node head = this.head;
if (head == null)
return head;
while (head != null) {
if (head.data == n) {
node head2 = head;
while (head2.next != null) {
if (head2.next.data % 2 != 0) {
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
}
if (head.data % 2 != 0) {
return head.next;
}
return head;
}
head = head.next;
}
return head;
}
Now I am trying to do a recursive function, I tried doing something but it seems like I am missing something.
My recursive function is
public node DeleteOddR(int n) {
node head = this.head;
if (head == null)
return head;
if (head != null) {
if (head.data == n) {
node head2 = head;
if (head2.next.data % 2 != 0)
{
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
if (head.data % 2 != 0) {
return DeleteOddR(head.next.data);
} else {
head.next = DeleteOddR(head.next.data);
return head;
}
} else {
head = head.next;
}
}
return head;
}
The results is
node f = l1.DeleteOddR(2);
display(f); // Gives- >2->3->4->6
I would appreciate helps..
I write one may meet your requirement .
Save the previous node and recurse using it .
public class LinkedList{
public static void main(String[] args) {
LinkedList node0 = new LinkedList(0);
LinkedList node1 = new LinkedList(1);
LinkedList node2 = new LinkedList(2);
LinkedList node3 = new LinkedList(3);
LinkedList node4 = new LinkedList(4);
LinkedList node5 = new LinkedList(5);
LinkedList node6 = new LinkedList(6);
LinkedList node7 = new LinkedList(7);
LinkedList node8 = new LinkedList(8);
node0.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
node6.setNext(node7);
node7.setNext(node8);
node0.removeOddFromVale(3, false);
System.out.println();
}
public void removeOddFromVale(int value,boolean start){
LinkedList head = this;
LinkedList prev = this;
if(!start){
while(head != null){
if(head.value == value){
start = true;
break;
}
prev = head;
head = head.next;
}
}
if(prev != null && head != null){
if(prev == head){
head = head.next;
}
if (head != null) {
if (head.value % 2 == 0) {
prev.next = head.next;
} else {
prev = prev.next;
head = head.next;
}
if (prev != null) {
prev.removeOddFromVale(value, true);
}
}
}
}
private LinkedList next;
private int value;
public LinkedList(int value){
this.value = value;
}
public LinkedList getNext() {
return next;
}
public void setNext(LinkedList next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
This question already has answers here:
How to reverse a singly-linked list in blocks of some given size in O(n) time in place?
(4 answers)
Closed 4 years ago.
Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly)
public void reverseList(){
Node before = null;
Node tmp = head;
Node next = tmp.next;
while(tmp != null){
if(next == null)
return;
tmp.next = before;
before = tmp;
tmp = next;
next = next.next;
}
}
And this is the Node class:
public class Node{
public int data;
public Node next;
public Node(int data, Node next){
this.data = data;
this.next = next;
}
}
On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.
Node next = tmp.next;
while(tmp != null){
So what happens when tmp == null?
You almost got it, though.
Node before = null;
Node tmp = head;
while (tmp != null) {
Node next = tmp.next;
tmp.next = before;
before = tmp;
tmp = next;
}
head = before;
Or in nicer (?) naming:
Node reversedPart = null;
Node current = head;
while (current != null) {
Node next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;
ASCII art:
<__<__<__ __ : reversedPart : head
(__)__ __ __
head : current: > > >
public Node<E> reverseList(Node<E> node) {
if (node == null || node.next == null) {
return node;
}
Node<E> currentNode = node;
Node<E> previousNode = null;
Node<E> nextNode = null;
while (currentNode != null) {
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
The method for reversing a linked list is as below;
Reverse Method
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
Three references are needed to reverse a list: pre, curr, incoming
... pre curr incoming
... --> (n-1) --> (n) --> (n+1) --> ...
To reverse a node, you have to store previous element, so that you can use the simple stament;
curr.next = pre;
To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed.
The demo code is as below;
LinkedList Sample Class
public class LinkedList<E> {
protected Node<E> head;
public LinkedList() {
head = null;
}
public LinkedList(E[] list) {
this();
addAll(list);
}
public void addAll(E[] list) {
for(int i = 0; i < list.length; i++)
add(list[i]);
}
public void add(E e) {
if(head == null)
head = new Node<E>(e);
else {
Node<E> temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = new Node<E>(e);
}
}
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
public void printList() {
Node<E> temp = head;
System.out.print("List: ");
while(temp != null) {
System.out.print(temp + " ");
temp = temp.next;
}
System.out.println();
}
public static class Node<E> {
protected E e;
protected Node<E> next;
public Node(E e) {
this.e = e;
this.next = null;
}
#Override
public String toString() {
return e.toString();
}
}
}
Test Code
public class ReverseLinkedList {
public static void main(String[] args) {
Integer[] list = { 4, 3, 2, 1 };
LinkedList<Integer> linkedList = new LinkedList<Integer>(list);
linkedList.printList();
linkedList.reverseList();
linkedList.printList();
}
}
Output
List: 4 3 2 1
List: 1 2 3 4
If this isn't homework and you are doing this "manually" on purpose, then I would recommend using
Collections.reverse(list);
Collections.reverse() returns void, and your list is reversed after the call.
We can have three nodes previous,current and next.
public void reverseLinkedlist()
{
/*
* Have three nodes i.e previousNode,currentNode and nextNode
When currentNode is starting node, then previousNode will be null
Assign currentNode.next to previousNode to reverse the link.
In each iteration move currentNode and previousNode by 1 node.
*/
Node previousNode = null;
Node currentNode = head;
while (currentNode != null)
{
Node nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
head = previousNode;
}
public void reverse() {
Node prev = null; Node current = head; Node next = current.next;
while(current.next != null) {
current.next = prev;
prev = current;
current = next;
next = current.next;
}
current.next = prev;
head = current;
}
// Java program for reversing the linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Function to reverse the linked list
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
OUTPUT: -
Given Linked list
85 15 4 20
Reversed linked list
20 4 15 85
I know the recursive solution is not the optimal one, but just wanted to add one here:
public class LinkedListDemo {
static class Node {
int val;
Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
#Override
public String toString() {
return "" + val;
}
}
public static void main(String[] args) {
Node n = new Node(1, new Node(2, new Node(3, new Node(20, null))));
display(n);
n = reverse(n);
display(n);
}
static Node reverse(Node n) {
Node tail = n;
while (tail.next != null) {
tail = tail.next;
}
reverseHelper(n);
return (tail);
}
static Node reverseHelper(Node n) {
if (n.next != null) {
Node reverse = reverseHelper(n.next);
reverse.next = n;
n.next = null;
return (n);
}
return (n);
}
static void display(Node n) {
for (; n != null; n = n.next) {
System.out.println(n);
}
}
}
I don't get it... why not doing this :
private LinkedList reverseLinkedList(LinkedList originalList){
LinkedList reversedList = new LinkedList<>();
for(int i=0 ; i<originalList.size() ; i++){
reversedList.add(0, originalList.get(i));
}
return reversedList;
}
I find this easier.
A more elegant solution would be to use recursion
void ReverseList(ListNode current, ListNode previous) {
if(current.Next != null)
{
ReverseList(current.Next, current);
ListNode temp = current.Next;
temp.Next = current;
current.Next = previous;
}
}
I tried the below code and it works fine:
Node head = firstNode;
Node current = head;
while(current != null && current.next != null){
Node temp = current.next;
current.next = temp.next;
temp.next = head;
head = temp;
}
Basically one by one it sets the next pointer of one node to its next to next node, so from next onwards all nodes are attached at the back of the list.
Node reverse_rec(Node start) {
if (start == null || start -> next == null) {
return start;
}
Node new_start = reverse(start->next);
start->next->next = start;
start->next = null;
return new_start;
}
Node reverse(Node start) {
Node cur = start;
Node bef = null;
while (cur != null) {
Node nex = cur.next;
cur.next = bef;
bef = cur;
cur = nex;
}
return bef;
}
I think your problem is that your initially last element next attribute isn't being changed becuase of your condition
if(next == null)
return;
Is at the beginning of your loop.
I would move it right after tmp.next has been assigned:
while(tmp != null){
tmp.next = before;
if(next == null)
return;
before = tmp;
tmp = next;
next = next.next;
}
Use this.
if (current== null || current.next==null) return current;
Node nextItem = current.next;
current.next = null;
Node reverseRest = reverse(nextItem);
nextItem.next = current;
return reverseRest
or Java Program to reverse a Singly Linked List
package com.three;
public class Link {
int a;
Link Next;
public Link(int i){
a=i;
}
}
public class LinkList {
Link First = null;
public void insertFirst(int a){
Link objLink = new Link(a);
objLink.Next=First;
First = objLink;
}
public void displayLink(){
Link current = First;
while(current!=null){
System.out.println(current.a);
current = current.Next;
}
}
public void ReverseLink(){
Link current = First;
Link Previous = null;
Link temp = null;
while(current!=null){
if(current==First)
temp = current.Next;
else
temp=current.Next;
if(temp==null){
First = current;
//return;
}
current.Next=Previous;
Previous=current;
//System.out.println(Previous);
current = temp;
}
}
public static void main(String args[]){
LinkList objLinkList = new LinkList();
objLinkList.insertFirst(1);
objLinkList.insertFirst(2);
objLinkList.insertFirst(3);
objLinkList.insertFirst(4);
objLinkList.insertFirst(5);
objLinkList.insertFirst(6);
objLinkList.insertFirst(7);
objLinkList.insertFirst(8);
objLinkList.displayLink();
System.out.println("-----------------------------");
objLinkList.ReverseLink();
objLinkList.displayLink();
}
}
You can also try this
LinkedListNode pointer = head;
LinkedListNode prev = null, curr = null;
/* Pointer variable loops through the LL */
while(pointer != null)
{
/* Proceed the pointer variable. Before that, store the current pointer. */
curr = pointer; //
pointer = pointer.next;
/* Reverse the link */
curr.next = prev;
/* Current becomes previous for the next iteration */
prev = curr;
}
System.out.println(prev.printForward());
package LinkedList;
import java.util.LinkedList;
public class LinkedListNode {
private int value;
private LinkedListNode next = null;
public LinkedListNode(int i) {
this.value = i;
}
public LinkedListNode addNode(int i) {
this.next = new LinkedListNode(i);
return next;
}
public LinkedListNode getNext() {
return next;
}
#Override
public String toString() {
String restElement = value+"->";
LinkedListNode newNext = getNext();
while(newNext != null)
{restElement = restElement + newNext.value + "->";
newNext = newNext.getNext();}
restElement = restElement +newNext;
return restElement;
}
public static void main(String[] args) {
LinkedListNode headnode = new LinkedListNode(1);
headnode.addNode(2).addNode(3).addNode(4).addNode(5).addNode(6);
System.out.println(headnode);
headnode = reverse(null,headnode,headnode.getNext());
System.out.println(headnode);
}
private static LinkedListNode reverse(LinkedListNode prev, LinkedListNode current, LinkedListNode next) {
current.setNext(prev);
if(next == null)
return current;
return reverse(current,next,next.getNext());
}
private void setNext(LinkedListNode prev) {
this.next = prev;
}
}
public class ReverseLinkedList {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("a");
linkedList.add("b");
linkedList.add("c");
linkedList.add("d");
linkedList.add("e");
linkedList.add("f");
System.out.println("Original linkedList:");
for(int i = 0; i <=linkedList.size()-1; i++){
System.out.println(" - "+ linkedList.get(i));
}
LinkedList<String> reversedlinkedList = reverse(linkedList);
System.out.println("Reversed linkedList:");
for(int i = 0; i <=reversedlinkedList.size()-1; i++){
System.out.println(" - "+ reversedlinkedList.get(i));
}
}
public static LinkedList<String> reverse(LinkedList<String> linkedList){
for(int i = 0; i < linkedList.size()/2; i++){
String temp = linkedList.get(i);
linkedList.set(i, linkedList.get(linkedList.size()-1-i));
linkedList.set((linkedList.size()-1-i), temp);
}
return linkedList;
}
}
To reverse a singly linked list you should have three nodes, top, beforeTop and AfterTop. Top is the header of singly linked list, hence beforeTop would be null and afterTop would be next element of top and with each iteration move forward beforeTop is assigned top and top is assigned afterTop(i.e. top.next).
private static Node inverse(Node top) {
Node beforeTop=null, afterTop;
while(top!=null){
afterTop=top.next;
top.next=beforeTop;
beforeTop=top;
top=afterTop;
}
return beforeTop;
}
Using Recursion It's too easy :
package com.config;
import java.util.Scanner;
public class Help {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Node head = null;
Node temp = null;
int choice = 0;
boolean flage = true;
do{
Node node = new Node();
System.out.println("Enter Node");
node.data = sc.nextInt();
if(flage){
head = node;
flage = false;
}
if(temp!=null)
temp.next = node;
temp = node;
System.out.println("Enter 0 to exit.");
choice = sc.nextInt();
}while(choice!=0);
Help.getAll(head);
Node reverse = Help.reverse(head,null);
//reverse = Help.reverse(head, null);
Help.getAll(reverse);
}
public static void getAll(Node head){
if(head==null)
return ;
System.out.println(head.data+"Memory Add "+head.hashCode());
getAll(head.next);
}
public static Node reverse(Node head,Node tail){
Node next = head.next;
head.next = tail;
return (next!=null? reverse(next,head) : head);
}
}
class Node{
int data = 0;
Node next = null;
}
Node Reverse(Node head) {
Node n,rev;
rev = new Node();
rev.data = head.data;
rev.next = null;
while(head.next != null){
n = new Node();
head = head.next;
n.data = head.data;
n.next = rev;
rev = n;
n=null;
}
return rev;
}
Use above function to reverse single linked list.
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
check more details about complexity analysis
http://javamicro.com/ref-card/DS-Algo/How-to-Reverse-Singly-Linked-List?
public static LinkedList reverseLinkedList(LinkedList node) {
if (node == null || node.getNext() == null) {
return node;
}
LinkedList remaining = reverseLinkedList(node.getNext());
node.getNext().setNext(node);
node.setNext(null);
return remaining;
}
/**
* Reverse LinkedList
* #author asharda
*
*/
class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
}
}
public class ReverseLinkedList {
static Node root;
Node temp=null;
public void insert(int data)
{
if(root==null)
{
root=new Node(data);
}
else
{
temp=root;
while(temp.next!=null)
{
temp=temp.next;
}
Node newNode=new Node(data);
temp.next=newNode;
}
}//end of insert
public void display(Node head)
{
while(head!=null)
{
System.out.println(head.data);
head=head.next;
}
}
public Node reverseLinkedList(Node head)
{
Node newNode;
Node tempr=null;
while(head!=null)
{
newNode=new Node(head.data);
newNode.next=tempr;
tempr=newNode;
head=head.next;
}
return tempr;
}
public static void main(String[] args) {
ReverseLinkedList r=new ReverseLinkedList();
r.insert(10);
r.insert(20);
r.insert(30);
r.display(root);
Node t=r.reverseLinkedList(root);
r.display(t);
}
}
public class SinglyLinkedListImpl<T> {
private Node<T> head;
public void add(T element) {
Node<T> item = new Node<T>(element);
if (head == null) {
head = item;
} else {
Node<T> temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = item;
}
}
private void reverse() {
Node<T> temp = null;
Node<T> next = null;
while (head != null) {
next = head.next;
head.next = temp;
temp = head;
head = next;
}
head = temp;
}
void printList(Node<T> node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String a[]) {
SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<Integer>();
sl.add(1);
sl.add(2);
sl.add(3);
sl.add(4);
sl.printList(sl.head);
sl.reverse();
sl.printList(sl.head);
}
static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
super();
this.data = data;
}
}
}
public class Linkedtest {
public static void reverse(List<Object> list) {
int lenght = list.size();
for (int i = 0; i < lenght / 2; i++) {
Object as = list.get(i);
list.set(i, list.get(lenght - 1 - i));
list.set(lenght - 1 - i, as);
}
}
public static void main(String[] args) {
LinkedList<Object> st = new LinkedList<Object>();
st.add(1);
st.add(2);
st.add(3);
st.add(4);
st.add(5);
Linkedtest.reverse(st);
System.out.println("Reverse Value will be:"+st);
}
}
This will be useful for any type of collection Object.
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;
Data structures class, implementing a singly linked-list with head, tail and current nodes. Having trouble with a method, could use a nudge in the right direction.
From the assignment, write the method:
add( item ) : adds the item (String) after the current node in the list and sets the current pointer to refer to the new node.
My attempt:
public void add(String item)
{
if(curr != null)
{
Node newNode = new Node(item, curr.next);
curr.next = newNode;
curr = newNode;
}
else
{
head = tail = new Node(item, null);
curr = head;
}
}
My add method only seems to work when I'm adding items to the middle of the list, not on either end. If I use it to add a few items and then print the list, only the first one I added will be on the list, while my prepend and append methods have tested just fine.
Is there any glaring issue with my code? I feel like I'm missing something obvious.
All:
public class LinkedList {
Node head = null; /* Head of the list */
Node tail = null; /* Tail of the list */
Node curr = null; /* Current node in the list */
public void prepend(String item) {
if (head == null) {
head = tail = new Node(item, null);
curr = head;
} else {
head = new Node(item, head);
curr = head;
}
}
public void append(String item) {
if (head == null) {
head = tail = new Node(item, null);
curr = tail;
} else {
tail.next = new Node(item, null);
tail = tail.next;
curr = tail;
}
}
public void add(String item) {
if (curr != null) {
Node newNode = new Node(item, curr.next);
curr.next = newNode;
curr = newNode;
} else {
head = tail = new Node(item, null);
curr = head;
}
}
public void delete() {
if (curr.next == null) {
Node temp = head;
while (temp.next != curr) {
System.out.println(temp.item);
temp = temp.next;
}
temp.next = null;
curr = head;
}
}
public void find(String item) {
Node temp = new Node(curr.item, curr.next);
if (item.equals(temp.item))
curr = temp;
else {
temp = temp.next;
while (temp.next != null && temp != curr) {
if (item.equals(temp.item))
curr = temp;
}
}
}
public String get() {
if (curr != null)
return curr.item;
else
return "";
}
public boolean next() {
if (curr != tail) {
curr = curr.next;
return true;
} else
return false;
}
public void start() {
curr = head;
}
public void end() {
curr = tail;
}
public boolean empty() {
if (head == null)
return true;
else
return false;
}
}
Node class:
class Node {
Node next;
String item;
Node(String item, Node next) {
this.next = next;
this.item = item;
}
}
There is indeed a problem in add: it doesn't update tail when nodes already exist. Consider this sequence of actions:
LinkedList list = new LinkedList();
list.add("one");
list.add("two");
list.append("three");
If you were to then print it using this:
public void print() {
Node curr = this.head;
while(curr != null) {
System.out.println(curr.item);
curr = curr.next;
}
}
Like this:
list.print();
You'd get the following output:
one
three
This happens because tail -- which append relies on -- continues to point to the first Node after the second add operation is performed.
I don't see any problems here, so I would guess the issue is elsewhere.
Okay, the only issue I see there is in delete:
public void delete()
{
Node temp = head;
while(temp != null && temp.next != curr) {
System.out.println(temp.item);
temp=temp.next;
}
if (temp != null && temp.next != null) {
temp.next = temp.next.next;
}
curr = head;
}
I think I have found your problem.
If you use append() you add it directly after the tail. But when you have added previous nodes after the tail you don't set your tail to the new node. This means that once you call append() twice you loose all the nodes that you have added after the first append().
Brief example:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("First add");
list.append("First Append");
list.add("Second add");
list.prepend("First prepend");
list.add("Third add");
list.prepend("Second prepend");
list.add("fourth add");
list.append("Second Append");
list.add("Fifth add");
list.add("Sixth add");
list.start();
do {
System.out.println(list.get().toString());
} while (list.next());
}
Output:
Second prepend
fourth add
First prepend
Third add
First add
First Append
Second Append
Conclusion: "Second Add" is lost, as well as "Fifth add" and "Sixth add" because your next() method stops as soon as it reaches the tail. You need to always update the tail if you add a new node in the end.
Hope this helps.
Cheers, Chnoch
I think the problem is
if (curr != null) {
Node newNode = new Node(item, curr.next); //<-- here (curr.next)
//and
Node(String item, Node next) {
this.next = next; //<-- here
Try (Edited):
Node newNode = new Node(item, curr); // pass curr to the constructor of Node
curr = newNode;