[LeetCode 19] Remove Nth Node from End of List (Medium)

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
-- Given n will always be valid.

Follow up:
-- Could you do this in one pass?

Solution

-- 快慢指针
-- 快指针先走n步,然后快慢指针同时再一起走。当快指针走到尾部时,慢指针后面那个节点,就是要删除的第n个节点。

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //Two pointer, firstly move fast pointer n steps, and then move slow and fast together, 
        // when fast reaches the end node, the nth node is the next node of the slow pointer.
        if (head == null || n < 1)
        {
            return head;
        }
        
        ListNode dummy = new ListNode (0);
        dummy.next = head;
        
        ListNode fast = dummy;
        ListNode slow = dummy;
        
        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 dummy.next;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容