leetcode 【 Remove Nth Node From End of List 】 python 实现
2024-08-29 13:53:29
题目:
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.
代码:oj在线测试通过 Runtime: 188 ms
# 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):
if head is None:
return head dummyhead = ListNode(0)
dummyhead.next = head
p1 = dummyhead
p2 = dummyhead for i in range(0,n):
p1 = p1.next while p1.next is not None:
p1 = p1.next
p2 = p2.next
if p1.next is None:
break p2.next = p2.next.next return dummyhead.next
思路:
Linked List基本都需要一个虚表头,这道题主要思路是双指针
让第一个指针p1先走n步,然后再让p1和p2一起走;当p1走到链表最后一个元素的时候,p2就走到了倒数n+1个元素的位置;这时p2.next向表尾方向跳一个。
注意下判断条件是p1.next is not None,因此在while循环中添加判断p1.next是否为None的保护判断。
再有就是注意一下special case的情况,小白我的习惯是在最开始就把这种case都判断出来;可能牺牲了代码的简洁性,有大神路过也请拍砖指点。
最新文章
- shell 中的与、或表达式
- struts2 CVE-2012-0392 S2-008 Strict DMI does not work correctly allows remote command execution and arbitrary file overwrite
- java 在接口里函数不能重载?
- 在strut.xml 中使用ognl
- C#删除文件和文件夹到回收站
- CentOS6.0/RedHat Server 6.4安装配置过程 详细图解!
- [数据库连接字符串] Access 连接字符串
- 微软开放技术开发了适用于 Windows Azure 移动服务的开源 Android SDK
- nvarchar and nchar
- Linux vim编辑器
- [LeetCode] Dota2 Senate 刀塔二参议院
- python之模块之shutil模块
- Tag
- java微信小程序调用支付接口(转)
- jquery 获取访问当前页面的开源设备信息
- python3之模块psutil系统性能信息
- oracle中验证身份证是否合法的函数脚本
- P03-Python装饰器
- 怎样在 Azure 应用服务中生成和部署 Java API 应用
- ARIA(Accessible Rich Internet Application)