Remove Nth Node From End of List

/**

* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {val = x;}
*}
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
if(head==null)
return head;
ListNode node
=new ListNode(0);
node.next
=head;
ListNode slow
=node;
ListNode fast
=node;
for(int i=0;i){
fast=fast.next;
}
if(fast==null)
return node.next;
while(fast.next!=null){
fast
=fast.next;
slow
=slow.next;
}
slow.next
=slow.next.next;
return node.next;

}
Imagine the linked list as a road where two people walk once on the road and traverse all the difference in the middle to get the point you are looking for

< span style="color: #008000;">/**

* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {val = x;}
*}
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
if(head==null)
return head;
ListNode node
=new ListNode(0);
node.next
=head;
ListNode slow
=node;
ListNode fast
=node;
for(int i=0;i){
fast=fast.next;
}
if(fast==null)
return node.next;
while(fast.next!=null){
fast
=fast.next;
slow
=slow.next;
}
slow.next
=slow.next.next;
return node.next;

}
Imagine the linked list as a road. Two people walking on the road at once traverse all the differences in the middle to get the point you are looking for

Leave a Comment

Your email address will not be published.