insert node at specific position using java - java

I'm doing the problem on hacker rank on inserting node at specific position. Im using java in this case, but I keep getting an error. And I don't know how to fix it. I appreciate your help. Here is my solution:
/*`enter code here`
Insert Node at a given position in a linked list
head can be NULL
First element in the linked list is at position 0
Node is defined as
class Node {
int data;
Node next;
}*/
Node InsertNth(Node head, int data, int position) {
`enter code here`// This is a "method-only" submission.
// You only need to complete this method.
if(head == null){
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
return head;
}
if(position == 1){
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
return head;
}
// we need to go to n - 1
int counter = 0;
Node currNode = head;
Node prevNode = null;
while(counter != position -1 && currNode.next != null){
prevNode = currNode;
currNode = currNode.next;
counter++;
}
Node nNode = new Node();
nNode.data = data;
prevNode.next = nNode;
nNode.next = currNode;
return head;
/* another solution */
}
Result:
Exception in thread "main" java.lang.NullPointerException
at Node.InsertNth(Solution.java:54)
at Solution.main(Solution.java:89)

In the code snippet that you have given, in comment you have mentioned that first element is at position 0. So in case insertion happens at position 0 then head will change. Thus the condition where you do
if(position == 1){
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
return head;
}
Yo should actually check position == 0. And the non stop repetition in your output that you are saying is because of this only. E.g if linked list 10->20 , I wish t insert 30 at position 0 , and we go by your code then we will not enter the loop as 0(counter) != -1 (position -1) so we prevNode and currNode both are pointing to 10 now and
Node nNode = new Node();
nNode.data = data;
prevNode.next = nNode; // you made 10 point to 30
nNode.next = currNode; // here you made 30 point to 10 so **loop** here

As far as I can see in the information you sent, the NullPointerException will happen if the flow don't get into the "while" loop, so the "prevNode" will remain null. Then you will get the exception in the "prevNode.next = nNode" line.
It will be easy to get if you debug the code.

Related

Null pointer Exception when writing a function for deleting a node at a specific position from a linked list in java

Below are my lines of code for deleting a node from a linked list.
Node Delete(Node head, int position) {
// Complete this method
int pos = 0;
Node current = head;
Node previous = null;
if(position == 0 && head.next == null){
return null;
}
if(head==null){
return null;
}
while(current.next!=null){
pos = pos + 1;
current = current.next;
if(pos==position){
previous.next = current.next;
}
previous = current;
}
return head;
}
What I am currently trying to do is declare two nodes current and previous. I initialized current to the head node of the linked list and previous to null. I have two if statements to deal with the tricky situation like the head being null and there being only one node in the linked list.
In the while loop, I have codes that is supposed to delete nodes other than in that in position 0. With the two nodes that I have declared above, I am simply trying to delete the node at certain position by setting up the previous pointer to point to the next node of current node.
However it's giving me a null pointer exception and I have gone out of ideas to see what actually went wrong to give me such an error. Any help from this community will be very appreciated.
Follow the other peer's comments for future community interactions.
Your problem is that you are not stopping the loop when you find the position:
Node Delete(Node head, int position) {
// Complete this method
int pos = 0;
Node current = head;
Node previous = null;
if(position == 0 && head.next == null){
return null;
}
if(head==null){
return null;
}
while(current.next!=null){
pos = pos + 1;
current = current.next;
if(pos==position){
previous.next = current.next;
break; // Terminate the Loop
}
previous = current;
}
return head;
}

Logic Error Inserting Node in Linked List (Java)

I am trying to learn to insert a node in a linked list (and return the head), but for some reason it is not correct.
This is my approach:
1. Create the new node with the desired data
2. If we want to insert it in the beginning, point this new node to the head and return the new node
3. Otherwise, loop to the position where we want to insert the node
- Once we get there, point the node to be inserted's next to the current node's next
- Point the current node to the node to be inserted
- Return the head
Why does this not work? Thanks so much!
Node InsertNth(Node head, int data, int position) {
Node node = new Node();
node.data = data;
if (position == 0) {
node.next = head;
return node;
}
else {
Node curr = head;
int currPos = 0;
while (currPos < position) {
curr = curr.next;
currPos++;
}
node.next = curr.next;
curr.next = node;
}
return head;
}
Given that you insert the new node after the curr node, this loop steps one node too far.
while (currPos < position) {
curr = curr.next;
currPos++;
}
You can easily work this out by stepping through through the code with a pen and paper, or with a debugger.
If you insert the node to the Head you need to set the Head to the node you're inserting.
Node InsertNth(Node head, int data, int position) {
Node node = new Node();
node.data = data;
if (position == 0) {
node.next = head;
head = node;
}
else {
Node curr = head;
int currPos = 0;
while (currPos < position) {
curr = curr.next;
currPos++;
}
node.next = curr.next;
curr.next = node;
}
return head;
}

How to determine the space and time complexity of these two double linked list algorithms?

I solved the next exercises having two solutions: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list
First (non-recursive):
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node Reverse(Node head) {
if (head == null) return null;
Node current = head;
while (current.next != null) {
Node temp = current.next;
current.next = current.prev;
current.prev = temp;
current = temp;
}
current.next = current.prev;
current.prev = null;
return current;
}
Second algorithm (recursive):
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node Reverse(Node head) {
if (head.next == null) {
head.next = head.prev;
head.prev = null;
return head;
}
Node newHead = Reverse(head.next);
Node temp = head.next;
head.next = head.prev;
head.prev = temp;
return newHead;
}
According to the book, the solution must be O(n). I guess using recursive solution is more elegant but maybe I'm wrong. Can you help to determine the space and time complexity of these two algoritms, or in your, which is better in performance?
The question is a bit unclear, both solutions seem to be O(n) in both time and space. Although you could probably remove the special cases and make Torvalds happy. Something like:
Node Reverse(Node head) {
if (head == null) return null;
Node current = head;
while (current != null) {
Node temp = current.next;
current.next = current.prev;
current.prev = temp;
current = temp;
}
return current;
}
Node Reverse(Node head) {
Node temp = head.next;
head.next = head.prev;
head.prev = temp;
return temp==null?head:Reverse(temp);
}
I have not tested these, use them as inspiration only. (Also the recursive will nullpointer if head is null in the beginning).

Inserting a node in a pre sorted linked list

I have been going through the Linkedlist problems on hacker rank and I am currently solving the question which will ask you to insert a node in a sorted doubly linkedlist.
This is my logic I wrote in Java
Node SortedInsert(Node head,int data) {
Node newNode = new Node();
Node temp = head;
newNode.data = data;
newNode.next = null;
newNode.prev = null;
if(head == null){
head = newNode;
}else{
while(data > temp.data && temp.next != null){
temp = temp.next;
}
if(temp == head){
newNode.next = temp;
temp.prev = newNode;
head = newNode;
}else if(data > temp.data){
newNode.prev = temp;
temp.next = newNode;
}else{
newNode.prev = temp.prev;
newNode.next = temp;
temp.prev.next = newNode;
temp.prev = newNode;
}
}
return head;
}
This is the error I get.
Your Output (stdout)
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function.
2. There is a problem with your logic
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function.
2. There is a problem with your logic
I have no idea what I did wrong. I really want to know where I went wrong. I know it is easy to find answer online but i think i will learn the best if someone can correct my mistake.
The problem is that you're always inserting the second element in the list before the first element. Consider the following illustration:
Let the linked list is empty initially. Now you follow your algorithm to insert 1. The head == null case is triggered and head points to newNode now.
x<-1->x
|
HEAD
Now, you try to insert 2 in the list. You'll see that the while loop ends and temp now points to head, triggering the if condition that follows (if(temp == head)).
x<-1->x
|
HEAD, temp
This inserts 2 (incorrectly!) before temp.
x<-2<=>1->x
|
HEAD
Swapping the order of the conditions should fix the problem:
if(data > temp.data) { // First, check if you need to insert at the end.
newNode.prev = temp;
temp.next = newNode;
} else if(temp == head) { // Then, check if you need to insert before head.
newNode.next = temp;
temp.prev = newNode;
head = newNode;
} else { // Otherwise, insert somewhere in the middle.
newNode.prev = temp.prev;
newNode.next = temp;
temp.prev.next = newNode;
temp.prev = newNode;
}

Can someone explain this Linked List Null Pointer Exception?

Node class
private class Node<E> {
E data;
Node<E> next;
public Node(E obj) {
data = obj;
next = null;
}
}
insert method (ascending order)
public void insert(E obj) {
Node<E> newNode = new Node<E>(obj);
Node<E> prev = null, curr = head;
while(curr != null && ((Comparable<E>)obj).compareTo(curr.data) >= 0) {
prev = curr;
curr = curr.next;
}
if(prev == null)
head = newNode;
else {
prev.next = newNode;
newNode.next = curr;
}
currentSize++;
}
remove method
public E remove() {
if(isEmpty())
return null;
E tmp = head.data;
head = head.next;
currentSize--;
return tmp;
}
I get Null Pointer Exception at the line
E tmp = head.data;
in the remove method
The error is fixed if the change the else statement in my insert method to
else
prev.next = newNode;
newNode.next = curr;
There's a problem when you insert a new node that needs to go at the beginning of the list (because it's smaller than the current head node). When you get to this part:
if(prev == null)
head = newNode;
you're setting head to be the new node you've just created, but you also need to set newNode.next to be the previous head. So you really want
if(prev == null) {
newNode.next = head;
head = newNode;
}
which inserts the new node at the beginning but tacks the previous head onto it.
With your code as it stands, when you add a second element that should go at the beginning, you're accidentally discarding the element that's already there, but you're still increasing currentSize; so you end up with a list with only one element, but a currentSize of 2. When you then try to remove two elements, the second one fails with a NullPointerException because you try to read the data inside a non-existent element.

Categories