Remove Nth Node From End of List
Description
Given a linked list, remove the nth node from the end of list and return its head.
Notice
The minimum number of nodes in list is n.
Example
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.
实现思路
这道题可以基于快慢指针来做,要删除第n个节点,可以设置一个快指针,让它先移动n步(此时在第n-1个节点),然后再设置一个慢指针从头开始,和快指针以相同速度前进,当快指针走到最后一个节点,慢指针恰好走到第n-1个节点,要删除第n个节点,直接令slow.next = slow.next.next
即可,这里假设是第n-1个节点必定存在。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = 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
ListNode behead = new ListNode(0);
behead.next = head;
ListNode slow = behead, fast = behead;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return behead.next;
}
}