In this linked list I am trying to delete a node and return the list after deleting the particular node. Here I am not using the Value to delete, I am using the position to delete that particular node. Here in my code the delete function seems to have no effect over the output. What am I doing wrong here?
import java.util.*; class LinkedList{ Node head; static class Node{ int data; Node next; Node(int d){ this.data = d; next = null; } } public LinkedList insert(LinkedList l, int data){ Node new_node = new Node(data); if(l.head == null){ l.head = new_node; } else{ Node last = l.head; while(last.next != null){ last = last.next; } last.next = new_node; } return l; } public LinkedList delete(LinkedList l, int position){ Node current = l.head; if(position == 0){ current = current.next; } int index = 1; while(index < position - 1){ current = current.next; index++; } current = current.next.next; Node iterating = l.head; while(iterating != null){ System.out.print(iterating.data + " "); iterating = iterating.next; } return l; } } public class Main { public static void main(String[] args) { LinkedList l = new LinkedList(); Scanner sc = new Scanner(System.in); int number = sc.nextInt(); int position = sc.nextInt(); for(int i=0; i<number; i++){ int num = sc.nextInt(); l.insert(l,num); } l.delete(l,position); } }
current = current.next.next;in yourdeletemethod is not then used.