• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Medium: 19. Remove Nth Node From End of List

一、题目

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

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.

给定一个链接的 list,移除从尾到头数的第 n 个结点。

二、思路

快慢指针,让快指针距离慢指针 n 的距离,然后快慢指针一块移动,然后当快指针移动到头的时候,慢指针所指的位置就是要删除的那个。

三、代码

#coding:utf-8
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def removeNthFromEnd(head, n):
    """
    :type head: ListNode
    :type n: int
    :rtype: ListNode
    """
    dummy = ListNode(0)
    dummy.next = head
    start = end = dummy
    for i in range(n):
        start = start.next
    while start.next:
        start = start.next
        end = end.next
    end.next = end.next.next
    return dummy.next

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-04-19 11:12  乐晓东随笔  阅读(137)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3