Deleting the second last node from a LinkedList in java - java

I'm working on a method that is supposed to delete the node prior to the last one,the logic seems quite fine with me, but when I tried to implement it in a project, it didn't work out. ( Oh and I'm using MyLinkedList)
here's the code:
public void deleteSec(){
Node current = head;
Node p = head.next;
Node q = null;
while(p.next!=null){
q = current;
current.next = p;
p = p.next;
}
q.next = p; // q.next = q.next.next;
}

What if your LL is empty? head will be null and this will cause an exception when you call head.next;
you have to take care of special cases like: empty LL, LL with one node, LL with two nodes.
Here is my code:
public void deleteSec() {
if (head == null) {
return;
}
if (head.next == null) {
return;
}
if (head.next.next == null) {
head = head.next;
return;
}
Node current = head;
Node p = current.next;
Node q = p.next;
while (q.next != null) {
current = current.next;
p = p.next;
q = q.next;
}
current.next = q;
}

if(myLinkedList.size() > 1) {
myLinkedList.remove(myLinkedList.size()-2);
}

well i personally compiled it,
Assuming the node class is named Node and you have a getNext() method that returns the next Node or null if this Node is the last node, you would do something like this.
if (head == null) // or if (first == null)
{
return; // There are no elements in the list.
}
Node currect = head; // This is the head, or Node current = first;
Node previous = null;
while (current.getNext() != null)
{
previous = current;
currrent = current.getNext();
}
Then do this to make the second to last pointer to next null.
if (previous != null)
{
previous.setNext( null );
}
else
{
// The list has 1 entry only.
head = null; // or first = null;
}

If deleting a second last node would be a common operation, as it is in my case, I would suggest an extra prev or previous node added to the Node construction.
Usually a linked list node would be
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
But I modified it to be like
private static class Node<Item> {
private Item item;
private Node<Item> prev;
private Node<Item> next;
}
Thus, if you want to delete the second last, the implementation would be pretty straightforward:
oldSecondLast = last.prev; // Assumes last points to the last node
oldSecondLast.next = last;
last = oldSecondLast.prev;
oldSecondLast = null; // To avoid loitering

Related

How can I add it delete Node First and delete Node Last

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.

How to delete the first node of doubly linked list

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);
}

inserting node in a linklist using java

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

Writing a method to sort a singly linkedlist in ascending order (java)

the method 'insertAscending' only gives me the first number even after i enter new ones. can anyone help with what i'm doing wrong? Thanks.
public class LinkedList13 {
// Private inner class Node
private class Node{
int data;
Node link;
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList13(){
head = null;
}
public void insertAscending(int data){
Node node = new Node();
node.data = data;
if (head == null)
head = node;
Node p = head;
while (p.link != null)
{
if (p.link.data > data)
{ node.link = p.link;
p.link = node;
break;
}
p= p.link;
}
}
}
Hint: is (p.link != null) ever true?
First of all, you should return after setting the head of the list (when the first element is added).
Second of all, you should handle the case where the newly inserted node is the smallest in the list (and therefore should come first). Your loop never compares the added node to the head of the list.
Finally, if the added element wasn't inserted in the while loop, it should be inserted after the while loop.
public void insertAscending(int data)
{
Node node = new Node();
node.data = data;
if (head == null) {
head = node;
return;
} else if (node.data < head.data) {
node.link = head;
head = node;
return;
}
Node p = head;
boolean added=false;
while (p.link != null)
{
if (p.link.data > data)
{
node.link = p.link;
p.link = node;
added = true;
break;
}
p = p.link;
}
if (!added)
p.link = node;
}
Check out your if condition if(p.link.data > data) the only way a node gets into the list is when that is true. This means, that, if the value of data being inserted it greater than (or equal to) everything that's been inserted so far, it will be discarded.
An easy way to fix this is change break to return and add p.link=node at the end (after the loop).

Inserting Node in a Sorted linked list

The following code ensures that elements are inserted in a linked list in a sorted manner.
After understanding the logic behind this i decided to test it on my own. However when i wrote my version of the code it as follows.
public class SortedList {
private Node first;
public SortedList() {
first = null;
}
public boolean isEmpty() {
return first == null;
}
public void insert(int j) {
Node newNode = new Node(j);
Node previous = null;
Node current = first;
while (current != null && j > current.iData) {
previous = current;
current = current.next;
}
if (previous == null)
first = newNode;
else
newNode.next = current;
previous.next = newNode;
}
public Node remove() {
Node temp = first;
first = first.next;
return temp;
}
public void displayList() {
System.out.println("First to -----> Last");
Node current = first;
while (current != null) {
current.display();
current = current.next;
}
}
}
NODE CLASS
public class Node {
public int iData;
public Node next;
public Node(int id) {
iData = id;
}
public void display() {
System.out.println(iData + " ");
}
}
TEST CLASS
public class SortedListApp {
public static void main(String[] args) {
SortedList list = new SortedList();
list.insert(20);
list.insert(40);
list.displayList();
list.insert(10);
list.insert(30);
list.insert(50);
list.displayList();
list.remove();
list.displayList();
}
}
The only difference between the two is that in my version when the while loop terminates. I first set the next value of the newNode to the current and then i set the next value of previous to the new Node. In the original code posted they have it reversed. For some reason this throws Null Pointer Exception. I am wondering why?
From what i understand, once the new node finds its place for insertion. We have reference to the previous node and the current node and we are trying to insert the new node in the middle of the previous and the current. Therefore what i do is set the next of the new Node to the current and then i set the next of previous node to the new node.
Please tell me where i am wrong.
Trace through this code when previous is null:
if (previous == null)
first = newNode;
else
newNode.next = current;
previous.next = newNode;
Notice that you never actually changed previous in the if statement, so this will try to write the next field of null, causing the crash.
If previous is null, then you need to prepend the node to the list, and in that case all you need to do is set first to newNode and make newNode's next pointer point to the old list. In the case where previous isn't null, then you need to do two rewirings: you need to make previous.next point to the new node and for the new node's next pointer to point to the current node. You can fix this by writing
if (previous == null) {
newNode.next = current;
first = newNode;
}
else {
newNode.next = current;
previous.next = newNode;
}
Equivalently:
newNode.next = current;
if (previous == null)
first = newNode;
else
previous.next = newNode;
Hope this helps!

Categories

Resources