-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1d94d81
commit 7404a9e
Showing
1 changed file
with
117 additions
and
0 deletions.
There are no files selected for viewing
117 changes: 117 additions & 0 deletions
117
Delete a Node in Single Linked List - GFG/delete-a-node-in-single-linked-list.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
//{ Driver Code Starts | ||
import java.util.*; | ||
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[]) | ||
{ | ||
|
||
Scanner sc = new Scanner(System.in); | ||
int t =sc.nextInt(); | ||
|
||
while(t>0) | ||
{ | ||
int n = sc.nextInt(); | ||
//int k = sc.nextInt(); | ||
DeleteNode llist = new DeleteNode(); | ||
//int n=Integer.parseInt(br.readLine()); | ||
int a1 = sc.nextInt(); | ||
Node head = new Node(a1); | ||
llist.addToTheLast(head); | ||
for (int i = 1; i < n; i++) | ||
{ | ||
int a = sc.nextInt(); | ||
llist.addToTheLast(new Node(a)); | ||
} | ||
int x = sc.nextInt(); | ||
//System.out.println(llist.head.data); | ||
GfG g = new GfG(); | ||
//System.out.println(k); | ||
//System.out.println(g.getNthFromLast(llist.head,k)); | ||
Node result = g.deleteNode(llist.head, x); | ||
llist.printList(result); | ||
t--; | ||
} | ||
} | ||
} | ||
// } Driver Code Ends | ||
|
||
|
||
/* 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 tmp=head; | ||
int c=2; | ||
int f=0; | ||
if(x==1) | ||
{ | ||
head=head.next; | ||
|
||
} | ||
else | ||
{ | ||
while(c<x) | ||
{ | ||
tmp=tmp.next; | ||
c++; | ||
|
||
} | ||
|
||
if(c==x) | ||
{ | ||
tmp.next=tmp.next.next; | ||
} | ||
|
||
} | ||
return(head); | ||
|
||
} | ||
} |