Remove Nth node from the end of the linkedlist
/**
* 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 sec = head;
while(n-->0){
first = first.next;
}
if(first ==null) return head.next;
ListNode temp = sec;
while(first!=null){
first = first.next;
temp = sec;
sec = sec.next;
}
temp.next = sec == null ? null : sec.next;
return head;
}
}
Top comments (0)