Thought:
Use two pointers, there distance is N. When the second pointer move to the end, the first pointer will point to the Node to be deleted.
To track the Node before the deleted node, initialize a previous pointer.
Code:
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = head;
ListNode second = head;
ListNode previous = head;
while(n > 1){
second = second.next;
n--;
}
while(second.next != null){
previous = first;
first = first.next;
second = second.next;
}
if(first != head){//deleting first
previous.next = first.next;
}else{//deleting head
head = head.next;
}
return head;
}
}
No comments:
Post a Comment