zoukankan      html  css  js  c++  java
  • 19. Remove Nth Node From End of List

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

    For 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.
    Try to do this in one pass

    题目说 one pass  ;    那么,这样,用两个直指针;    p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。

    Calculate the length first, and then remove the nth from the beginning.

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null)
            return null;
     
        //get length of list
        ListNode p = head;
        int len = 0;
        while(p != null){
            len++;
            p = p.next;
        }
     
        //if remove first node
        int fromStart = len-n+1;
        if(fromStart==1)
            return head.next;
     
        //remove non-first node    
        p = head;
        int i=0;
        while(p!=null){
            i++;
            if(i==fromStart-1){
                p.next = p.next.next;
            }
            p=p.next;
        }
     
        return head;
    }

    Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null)
            return null;
     
        ListNode fast = head;
        ListNode slow = head;
     
        for(int i=0; i<n; i++){
            fast = fast.next;
        }
     
        //if remove the first node
        if(fast == null){
            head = head.next;
            return head;
        }
     
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
     
        slow.next = slow.next.next;
     
        return head;
    }

    解题思路:加一个头结点dummy,并使用双指针p1和p2。p1先向前移动n个节点,然后p1和p2同时移动,当p1.next==None时,此时p2.next指的就是需要删除的节点。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @return a ListNode
        def removeNthFromEnd(self, head, n):
            dummy=ListNode(0); dummy.next=head
            p1=p2=dummy
            for i in range(n): p1=p1.next
            while p1.next:
                p1=p1.next; p2=p2.next
            p2.next=p2.next.next
            return dummy.next
  • 相关阅读:
    Go使用dlv调试代码
    1660 super安装tensorflow1.15
    SQL Server高级进阶之表分区删除
    SQL Server高级进阶之分区表创建
    SQL Server高级进阶之索引优化查询
    SQL Server高级进阶之索引碎片维护
    C# WinForm通用自动更新器
    获取当前月第一天,当前月最后一天,上个月日期,上个月的第一天
    去除checkbox选择的三种方式
    用SpringBoot实现策略模式
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/5279867.html
Copyright © 2011-2022 走看看