Delete in a Singly Linked List GFG problem
Delete in a Singly Linked List
Given a singly linked list and an integer, x. Delete the xth node (1-based indexing) from the singly linked list.
Examples:
Input: Linked list: 1 -> 3 -> 4, x = 3
Output: 1 -> 3
Explanation: After deleting the node at the 3rd position (1-base indexing), the linked list is as 1 -> 3.
Input: Linked list: 1 -> 5 -> 2 -> 9, x = 2
Output: 1 -> 2 -> 9
Explanation: After deleting the node at 2nd position (1-based indexing), the linked list is as 1 -> 2 -> 9.
//{ Driver Code Starts
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class DeleteNode {
Node head;
void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public void addToTheLast(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = node;
}
}
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while (t > 0) {
String[] s = in.readLine().trim().split(" ");
Node head = new Node(Integer.parseInt(s[0]));
Node copy = head;
for (int i = 1; i < s.length; i++) {
Node temp = new Node(Integer.parseInt(s[i]));
copy.next = temp;
copy = copy.next;
}
int x = Integer.parseInt(in.readLine());
Solution ob = new Solution();
Node ans = ob.deleteNode(head, x);
while (ans != null) {
System.out.print(ans.data + " ");
ans = ans.next;
}
System.out.println();
System.out.println("~");
t--;
}
}
}
// } Driver Code Ends
/* Linklist node structure
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}*/
class Solution {
Node deleteNode(Node head, int x) {
// code here
int position=x;
if (head == null) {
//System.out.println("List is empty");
return null;
}
if (position == 1) { // Delete head
head = head.next;
return head;
}
Node temp = head;
for (int i = 1; temp != null && i < position - 1; i++) {
temp = temp.next;
}
if (temp == null || temp.next == null) {
// System.out.println("Invalid position");
return head;
}
temp.next = temp.next.next; // Bypass the target node
return head;
}
}
Comments
Post a Comment