Delete a Node in Single Linked List Geeks
Problem :
Delete node at ith position in a linked list.
Idea
Start a loop till we got to 1 position before the position to be deleted.
Code:
/* Linklist node structure
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}*/
/*You are required to complete below method*/
class GfG
{
Node deleteNode(Node head, int x)
{
Node root=head;
int count=2;
if(x==1)
return head.next;
while(head.next!=null && count++<x)
{
head=head.next;
}
head.next=head.next.next;
return root;
}
}
0 Comments:
Post a Comment