zoukankan      html  css  js  c++  java
  • 删除链表的倒数第N个节点

    一、题目描述

     给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

     示例:

      给定一个链表:1->2->3->4->5,和 n = 2.

      当删除了倒数第二个节点后,链表变为 1->2->3->5

     方法一:两遍遍历,第一遍求出链表长度

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            first = head
            length = 0
            while first:#求长度
                length += 1
                first = first.next
                
            if length == 1:#如果长度为1,则n等于1
                head = None
                return head
            
            if length == n:#如果长度和n相等,则删除的是第一个节点
                head = head.next
                return head
            
            flag = 1
            pre = head
            cur = head.next
            while (flag < length - n):
                flag += 1
                pre = cur
                cur = cur.next
            pre.next = cur.next
            return head
    

     方法二:一遍遍历

      使用两个指针。第一个指针从列表的开头向前移动 n+1步,而第二个指针将从列表的开头出发。现在,这两个指针被 n个结点分开。

      我们通过同时移动两个指针向前来保持这个恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后一个结点数起的第 n 个结点。我们重新链接第二个指针所引用的结点的 next 指针指向该结点的下下个结点。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            if not head or n<1:
                return None
            fast=head
            slow=head
            for _ in range(n):
                if not fast:
                    return None
                fast=fast.next
            if not fast:
                return head.next
            while fast.next:
                fast=fast.next
                slow=slow.next
            slow.next=slow.next.next
            return head
    

      

  • 相关阅读:
    linux最常用命令记录(一)
    2020centos解决“nginx 403 Forbidden"错误的故事
    nginx显示静态html爆502 bad gateway的错误提示
    codeigniter框架的使用感受和注意事项
    网闸
    抗DDOS防火墙
    负载均衡
    上网行为管理
    漏洞扫描系统
    网络分析系统
  • 原文地址:https://www.cnblogs.com/always-fight/p/10302641.html
Copyright © 2011-2022 走看看