I am solving the well known problem Remove Nth Node From End of List:
Given a linked list, remove the n-th node from the end of list and return its head. Assume that n is between 0 and the length of the list.
Example:
Given: 1->2->3->4->5, and n = 2 Return: 1->2->3->5.
This is my solution:
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || n == 0)
return head;
ListNode slow = head;
ListNode fast = head;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode pre = newHead;
int steps = 1;
while(steps <= n){
fast = fast.next;
steps++;
}
if(fast == null)
return head.next;
while(fast.next != null){
pre = pre.next;
slow = slow.next;
fast = fast.next;
}
if(slow.next != null)
slow.next = slow.next.next;
else // slow.next = null, i.e. I have to remove the last node
pre.next = null;
return head;
}
and this is the definition of ListNode
class:
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
What I don't like in my code is that I handle every edge case separately. Is there more sophisticated way to deal with the edge cases? Also the following code fragment:
while(steps <= n){
fast = fast.next;
steps++;
}
Is this the right condition for traversing the list? This definitely works, but is it better to rewrite my code in terms of
while(steps < n){
fast = fast.next;
steps++;
}