I'm trying to implement a basic doubly-linked-list using nothing but the primitive types and classes. I was trying to create a doubly linked list where a new element can only be inserted at the end, although it can be deleted from any position, (based on a value that is searched throughout the list). My code is:
import java.util.*;
class node {
int data;
node next;
node prev;
static void insert(node start, int data)
{
node newNode = new node();
newNode.data = data;
if(start==null) {
newNode.next=newNode.prev=null;
start = newNode;
} else {
node t = start;
while(t.next!=null)
t = t.next;
newNode.prev = t;
t.next = newNode;
newNode.next=null;
}
}
static void delete(node start, int data) {
node t = start;
try {
while(t.data!=data)
t = t.next;
t.prev.next = t.next;
t.next.prev = t.prev;
} catch (NullPointerException e) {
System.out.println("Data NOT found!");
}
}
static void traverse(node start) {
node t = start;
while(t!=null) {
System.out.println(t.data);
t=t.next;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
node start=null;
int ch=0;
while(ch!=4)
{
System.out.println("\n1. Insert Node");
System.out.println("2. Delete Node");
System.out.println("3. Print nodes");
System.out.println("4. Exit!");
System.out.print("Enter Your Choice: ");
ch = sc.nextInt();
switch(ch)
{
case 1: System.out.print("\nEnter the value of the node to insert: ");
int val = sc.nextInt();
node.insert(start, val);
System.out.println("DEBUG : Start val: "+start.data);
break;
case 2: System.out.print("\nEnter the value of the node you want to delete: ");
node.delete(start, sc.nextInt());
break;
case 3: node.traverse(start);
break;
case 4: System.out.println("\nBye!!");
break;
default: System.out.println("\nWrong value: Please try again!");
}
}
}
}
I get an error:
Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:70)
It appears that the node start
that I've defined in main() method doesn't really obtain the value stored by the insert()
function. I'm guessing this is due to the fact that the updated value of start
in the insert
function, i.e., start = newNode;
isn't really stored in the start var of the main method. This seems odd however, since in Java, the objects are supposed to retain their changed values given that their addresses are passed to the methods, and any change in the memory locations where the actual data of the object is stored is permanent. So, what is going on here? Am I doing something wrong?!
Here's stdin:
1 1 1 2 1 3 3 2 2 3 4
Here's my output:
- Insert Node
- Delete Node
- Print nodes
- Exit! Enter Your Choice: Enter the value of the node to insert:
Here's a gist of the code on IDEOne.