-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRemoveNthNodeFromEnd.java
More file actions
44 lines (43 loc) · 1.12 KB
/
RemoveNthNodeFromEnd.java
File metadata and controls
44 lines (43 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//Solve this Problem in leet code platform
//Link :- https://leetcode.com/problems/remove-nth-node-from-end-of-list/
//Time Complexity O(N) N = Number Of Nodes in LinkedList
//Space Complextiy O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = head;
ListNode second = head;
int counter = 1;
if(head==null)
{
return head;
}
while(counter <= n)
{
second = second.next;
counter++;
}
if(second == null)
{
head.val=head.next.val;
head.next = head.next.next;
return head;
}
while(second.next != null)
{
first = first.next;
second = second.next;
}
first.next = first.next.next;
return head;
}
}