leetcode 19 题解 翻译 Python版
来源:互联网 发布:淘宝一元秒杀验证码 编辑:程序博客网 时间:2024/06/12 01:01
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.
Example 1:
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:
1. Given n will always be valid.
2. Try to do this in one pass.
题目翻译
给定一个排好序的链表,删除从后往前数的第n个节点并且返回删除后的链表头指针。
示例1:
给定的链表:1->2->3->4->5,n = 2删除倒数第2个节点后的链表:1->2->3->5
注意:
1. 给定的链表总是正确的
2. 在一次遍历中完成操作
解题方案
标签: Linked List
思路:
- 本题需要维护两个指针,pre和end。一开始初始化时使得pre指针指向链表头节点,end指针指向pre+n的节点位置。然后同时往后移动pre和end指针位置,使得end指针指向最后一个节点,那么pre指针指向的则是end-n的节点位置(即倒数第n个元素的前一个节点),则将其删除。
- 链表长度为n时,算法复杂度O(n)。
代码:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ pre = head end = head for _ in range(n): end = end.next if end is None: # 需要删除的节点为第一个节点时,即返回第二个节点为头节点的链表 return head.next while end.next is not None: pre = pre.next end = end.next pre.next = pre.next.next return head
阅读全文
0 0
- leetcode 19 题解 翻译 Python版
- leetcode 27 题解 翻译 Python版
- leetcode 154 题解 翻译 Python版
- LeetCode题解汇总(C++ Java Python,含题目翻译)
- leetcode 题解 翻译 C语言 Python 合集 (不断更新)
- leetcode 部分题解(python)
- leetcode292题 题解 翻译 C语言版 Python版
- leetcode258题 题解 翻译 C语言版 Python版
- leetcode104题 题解 翻译 C语言版 Python版
- leetcode237题 题解 翻译 C语言版 Python版
- leetcode226题 题解 翻译 C语言版 Python版
- leetcode283题 题解 翻译 C语言版 Python版
- leetcode100题 题解 翻译 C语言版 Python版
- leetcode242题 题解 翻译 C语言版 Python版
- leetcode171题 题解 翻译 C语言版 Python版
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode206题 题解 翻译 C语言版 Python版
- leetcode328题 题解 翻译 C语言版 Python版
- HDFS-数据块
- opencv图像开运算闭运算/腐蚀膨胀
- Django编写RESTful API(一):序列化
- 注册表------数据结构--数据库
- cmd编译运行java无法加载主类(前提:环境变量没问题,主函数没问题)
- leetcode 19 题解 翻译 Python版
- C#3.0 之扩展方法
- Md5Util 加密工具类
- OkHttp二次封装
- 域名系统DNS总结
- 剑指offer 50 把字符串转换成整数
- hiho一下 第173周 题目1 : A Game 【区间dp】
- 【20171025中】alert(1) to win 脚本渲染自建
- 转载安装theano后GPU配置的各种坑