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.
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end,
the linked list becomes 1->2->3->5->null.
分析:
画图确定特殊情况
解法:
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if (n <= 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
if (fast == null) {
return dummy.next;
}
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}