Remove Nth Node From End of List(删除链表中倒数第n个节点)

问题

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.

Have you met this question in a real interview? Yes
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的尺子,在没有构建完成前如果为null就返回null,构建完成之后每次平移整个尺子,最后就找到要删除的前一个接点。然后进行删除操作。

代码

/**
 * 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 node=new ListNode(0);
        node.next=head;
        for(int i=0;i

你可能感兴趣的:(Remove Nth Node From End of List(删除链表中倒数第n个节点))