• 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
  • 相关阅读:
    cron表达式详解(转载)
    Swagger 3.0使用教程(转载)
    springboot整合shiro-对密码进行MD5并加盐处理(十五)(转载)
    redis排序
    引用和指针的区别?
    测试策略
    主键、外键的作用,索引的优点与不足?
    您所熟悉的软件测试类型都有哪些?请试着分别比较这些不同的测试类型的区别与联系(如功能测试、性能测试……)
    UI测试测什么
    数据库,数据库管理系统,数据库系统三者的区别和练习?
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/5279867.html
Copyright © 2020-2023  润新知