would anybody be able to help me with this problem I've been having? I'm trying to implement a doubly linked list for the first time and have been frustrated trying to get my code to work for my remove class:
public void remove(int data) {
if(length == 0) {
return;
}
if (head.data == data){
head = head.next;
length--;
}
Node current = head;
while (current != null) {
if(current.data != data) {
current = current.next;
length--;
}
current = current.next;
}
}
I know this question may have been asked before, but I was unable to understand the differences in other people's code as it was much more complex. It's been a really difficult day trying to get this one method working without getting a NullPointerException and help would be appreciated! Thanks.
You want to remove a single node or part of the front list?
If you are trying to remove a single node, your current node is used as a pointer to find the node to be removed, when you find such node, you can change the node's value, if this is the last element, you can set the previous node's next node to null, else set the previous nodes' next node to the node's next node, and change the node's next node's previous node to the node's previous node.
public void remove(int data) {
if(length == 0) {
return;
}
if (head.data == data){
head = head.next;
length--;
}
Node current = head;
while (current != null) {
if (current.data != data) {
current = current.next;
} else {
if (current.next == null) {
current.pre.next = null;
} else {
current.pre.next = current.next;
current.next.pre = current.pre;
}
length--;
}
}
}
Try this:
public void remove(int data) {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (this.size == 1 && this.head.getData() == data) {
this.head = this.tail = null;
this.size--;
return;
}
if (this.head.getData() == data) {
this.head = this.head.getNext();
this.head.setPrevious(null);
this.size--;
return;
}
if (this.tail.getData() == data) {
this.tail = this.tail.getPrevious();
this.tail.setNext(null);
this.size--;
return;
}
for (Node<T> current = this.head; current != null; current = current.getNext()) {
if (current.getData() == data) {
Node<T> previous = current.getPrevious();
Node<T> next = current.getNext();
previous.setNext(next);
next.setPrevious(previous);
this.size--;
return;
}
}
throw new NoSuchElementException();
}
Related
How can I add it and delete Node First and delete Node Last in a double-link list
Just want to add delete Node First and delete Node Last. I did not know how to add it in your programming, but I want to help it solve it
i have 3 class
class node .
class doublyLinkedListMain .
class doublyLinkedList .
I want to add special programming in class doublyLinkedList this one delete Node First and delete Node Last
class doublyLinkedList
{
Node head;
public void push(int newdata)
{
Node NewNode = new Node(newdata);
NewNode.next = head;
NewNode.prev = null;
if (head != null) head.prev = NewNode;
head = NewNode;
}
public void insertAfter(Node PrevNode, int newdata)
{
if (PrevNode == null)
{
System.out.println("The given previous node cannot be null");
return;
}
Node NewNode = new Node(newdata);
NewNode.next = PrevNode.next;
PrevNode.next = NewNode;
NewNode.prev = PrevNode;
if (NewNode.next != null)
NewNode.next.prev = NewNode;
}
public void append(int newdata)
{
Node NewNode = new Node(newdata);
Node last = head;
NewNode.next = null;
if (head == null)
{
NewNode.prev = null;
head = NewNode;
return;
}
while (last.next != null) last = last.next;
last.next = NewNode;
NewNode.prev = last;
return;
}
void insertBefore(Node NextNode, int newdata)
{
if (NextNode == null)
{
System.out.println("the given next node cannot be NULL");
return;
}
Node NewNode = new Node(newdata);
NewNode.data = newdata;
NewNode.prev = NextNode.prev;
NextNode.prev = NewNode;
NewNode.next = NextNode;
if (NewNode.prev != null)
NewNode.prev.next = NewNode;
else head = NewNode;
}
void deleteNode( Node del)
{
if (head == null || del == null) return;
if (head == del) head = head.next;
if (del.next != null) del.next.prev = del.prev;
if (del.prev != null) del.prev.next = del.next;
return;
}
void printList()
{
Node n = head;
while (n != null)
{
System.out.print(n.data+" ");
n = n.next;
}
System.out.print(" \n ") ;
}
}
sorry, but you have different mistakes in your code. Firstly, for a list you need two or three pointers as attribute in your List class (Node head /* begin */, tail /* end */, current /* yes, the current element on which you have access */ - I have learned it with a current pointer but depending on your implementation you can do it without it too). Because of that, you must change some of your code. For example, you need a hasAccess() : boolean method, if you use a current pointer, which return current != null and your methods must consider and use tail. Furthermore, you should add a method isEmpty():
public boolean isEmpty() {
return head == null;
}
This method checks if the list is empty. In the case, that the list is empty (the method returns true), you cannot do some things, but you had seen that yet. But, because of the new pointer tail, you have its much easier to delete the last Node (see below).
Please, change all your attributes to private and code a getter and a setter for each of them. For example in the class Node for the attribute next:
private Node next;
// other code...
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
I have solved the problem with "delete Node First and delete Node Last" in the following way:
public class DoublyLinkedList {
private Node head; // begin
private Node tail; // end
public void deleteFirstElement() {
if (!isEmpty()) {
head = head.getNext();
}
}
public void deleteLastElement() {
if (!isEmpty()) {
tail = tail.getPrev();
}
}
// other code
}
Of course, you have to proof your other code, if it works. I hope that I could help you.
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 have an implementation of doubly linked list , and I'm trying to delete a particular node at a given position. I managed to delete the second node to the last node but when I try to delete the first node it fails, I wonder what's wrong with my code.
I've already tried this but still doesn't work
head.next.previous = null;
head = head.next;
This is my code
public class Proses {
private class Node{
String Matkul;
int NilaiUts;
int NilaiUAS;
Node previous;
Node next;
public Node(String Matkul, int Nilai, int NilaiUAS) {
this.Matkul = Matkul;
this.NilaiUts = Nilai;
this.NilaiUAS = NilaiUAS;
}
}
Node head, tail = null;
public void addNode(String matkul, int Nilai, int NilaiUAS) {
Node newNode = new Node(matkul, Nilai, NilaiUAS);
if(head == null) {
head = tail = newNode;
head.previous = null;
tail.next = null;
} else {
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
tail.next = null;
}
}
public void delete(int position){
if (head == null || n <= 0)
return;
Node current = head;
int i;
for (i = 1; current != null && i < position; i++)
{
current = current.next;
}
if (current == null)
return;
deleteNode(head, current);
}
//delete function
public Node deleteNode(Node head, Node del){
if (head == null || del == null){
return null;
}
if (head == del){
head = del.next;
del.next.previous = null;
}
if (del.next != null){
del.next.previous = del.previous;
}
if (del.previous != null){
del.previous.next = del.next;
}
del = null;
return head;
}
}
Using your code, if the scenario is such that it ends up with 1 node (head will be pointing to this node) and you want to delete this node (i.e. head), code will fail with NullPointerException at
del.next.previous = null;
as del.next is NULL;
Use can take a look at below code to delete a Node from doubly linked list
// Function to delete a node in a Doubly Linked List.
// head_ref --> pointer to head node pointer.
// del --> data of node to be deleted.
void deleteNode(Node head_ref, Node del)
{
// Base case
if (head == null || del == null) {
return;
}
// If node to be deleted is head node
if (head == del) {
head = del.next;
}
// Change next only if node to be deleted
// is NOT the last node
if (del.next != null) {
del.next.prev = del.prev;
}
// Change prev only if node to be deleted
// is NOT the first node
if (del.prev != null) {
del.prev.next = del.next;
}
// Finally, free the memory occupied by del
return;
}
code ref: https://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/
The problem with your code is that, head is not getting changed in deleteNode function because it's pass by value. Consider the following scenario:
You are deleting the position 1. Head is pointing to the node1, so
it store the address of node1. assume it's 1001.
Now you call deleteNode function with head reference and currentNode, so head reference is get passed to the function argument as pass by value. so in function argument head contains the address 1001.
Now you perform the delete operation, so the function's head is changing it's position to the next node. But, your class member's head is still pointing to the first position.
To overcome this, you can set the head again, because you are returning it from the deleteNode function. Like:
Change the code as follow
public void delete(int position){
if (head == null || n <= 0)
return;
Node current = head;
int i;
for (i = 1; current != null && i < position; i++)
{
current = current.next;
}
if (current == null)
return;
head = deleteNode(head, current);
}
I'm trying to better undserstand my teachers notes on how to delete a node from a doubly linked list, what she had on the boards is
public void deleteNode(Node D){
Node current = head;
while(current.data != D.data && current.next != null){
current = current.next;
}
d.prev.next = d.next;
d.next.prev = current.prev.
}
I can't help but feel like this isn't enough to remove a node. I was thinking maybe she meant
current.prev.next = d.next and
current.next.prev = d.prev
Once I figure out how to understand this better would it make sense if I wanted to delete a node from the middle by doing
public void deleteMiddle(){
Node current = head;
int i = 0;
while(i < size/2){
current = current.next;
i++;
}
deleteNode(current);
}
The correct way would be to either pass in the value, i.e. the data, or to make the method private, to protect against misuse.
Or do both:
public void deleteNode(int data) {
Node current = head;
while (current != null && current.data != data) {
current = current.next;
}
deleteNode(current);
// Note: We silently do nothing if 'data' not found
}
private void deleteNode(Node node) {
if (node != null) {
// Here we can rely on 'node' actually being in our list
if (node.prev != null)
node.prev.next = node.next;
else
head = node.next;
if (node.next != null)
node.next.prev = node.prev;
else
tail = node.prev;
}
}
I m beginner at java. I am trying to implement simple linklist structure using java.
I have written following code that inserts node at the end of the linklist.
public static Node insert(Node head,int data) {
if(head == null)
{
Node temp = new Node(data);
head = temp;
return head;
}
else
{
Node temp = new Node(data);
Node current = head;
while(current != null)
{
current = current.next;
}
current = temp;
return head;
}
}
The Node class is defined as follows
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
The class LinkListDemo has the insert(),display() and main() method as follows..
class LinkListDemo
{
public static Node insert(Node head,int data) {
if(head == null)
{
Node temp = new Node(data);
head = temp;
return head;
}
else
{
Node temp = new Node(data);
Node current = head;
while(current != null)
{
current = current.next;
}
current = temp;
return head;
}
}
public static void display(Node head) {
Node start = head;
while(start != null) {
System.out.print(start.data + " ");
start = start.next;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Node head = null;
int N = sc.nextInt();
while(N-- > 0) {
int ele = sc.nextInt();
head = insert(head,ele);
}
display(head);
sc.close();
}
}
INPUT: 4 2 3 4 1
I gave input as 4(number of nodes to be inserted) 2 3 4 1(corresponding node values)
I expected output to be 2 3 4 1
but the output is only 2.
Please help me to correct my mistake. Thanks in advance.
The problem is in the else part of your insert method. You are looping till current becomes null and then assign the new node temp to it. Assigning the reference to the new node(temp) will not append (or link) to the end of the list.
The correct way is to go to the last node and then link the new node i.e, make the last node's next point to the new node.
It should be like
while(current.next != null) {
current = current.next;
}
current.next = temp;
In your code for insert(), you should have
while(current.next != null)
{
current = current.next;
}
In your code, your current variable will always end up being null, resulting in your node not actually being inserted. This fix makes your current variable the last node in the list, so that you can set the last node's pointer to your new node.
I am inserting node using following code
public void addFirst(int e) {
if (head == null) {
head = new LinkListNode(e);
tail = head;
size = 1;
} else {
LinkListNode nextNode = new LinkListNode(e);
nextNode.setNext(head);
head = nextNode;
size++;
}
}
Working fine...
Just Change little bit code
Node current = head;
while(current.next != null)
{
current = current.next;
}
current.next= temp;
and return head