lintcode-easy-Remove Nth Node from End of List

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Remove Nth Node from End of List相关的知识,希望对你有一定的参考价值。

Given a linked list, remove the nth 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.
 
因为要删除的节点可能是head,所以要使用一个fakehead
/**
 * 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 fakehead = new ListNode(0);
        fakehead.next = head;
        ListNode fast = fakehead;
        for(int i = 0; i <= n; i++)
            fast = fast.next;
        
        ListNode slow = fakehead;
        while(fast != null){
            slow = slow.next;
            fast = fast.next;
        }
        
        slow.next = slow.next.next;
        return fakehead.next;
    }
}

 

以上是关于lintcode-easy-Remove Nth Node from End of List的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-easy-Remove Duplicates from Sorted Array

lintcode-easy-Remove Linked List Elements

lintcode-easy-Remove Duplicates from Sorted List

CSS选择器之:nth-child()和:nth-of-type()的使用

如何根据 tr:nth-child(7) > td:nth-child(2) 的内容隐藏特定的 tr:nth-child(6)

CSS3中:nth-child和:nth-of-type的区别深入理解