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
  • 相关阅读:
    C#中 类的多态
    字段与属性
    C# ASCII与字符串间相互转换
    TextBox控件常用方法总结
    使用hadoop mapreduce分析mongodb数据:(2)
    使用hadoop mapreduce分析mongodb数据:(1)
    Linux MPI集群配置
    VIM文本替换
    怎么解决python中TypeError: can't pickle instancemethod objects的这个错误
    LeetCode ZigZag problem
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/5279867.html
Copyright © 2011-2022 走看看