leetcode_19. Remove Nth Node From End of List 删除单链表中的倒数第n个节点,双指针法
来源:互联网 发布:macbook 自带软件 编辑:程序博客网 时间:2024/06/07 17:37
题目:
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.
题意:
给定一个单链表和整数n,删除单链表中的倒数第n个节点,要求只遍历一遍。
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if n <= 0 :
return head
else :
p_node = ListNode(0) #通过双指针p和q确定距离n,当p指到空时,q指的就是倒数第n个节点
q_node = ListNode(0)
p_node = head
q_node = head
for i in range(n) : #使p,q的距离为n
p_node = p_node.next
if p_node == None : #考虑特殊情况,如果链表总长度是n,要删除倒数第n个,即删除头结点,则需要修改head
head = head.next
else : #否则,head不需要修改,通过修改q的指向直接删除倒数第n个节点
while p_node.next != None :
q_node = q_node.next
p_node = p_node.next
q_node.next = q_node.next.next
return head
笔记:
1、双指针的思想,通过双指针保持距离n,找到倒数第n个节点
2、考虑n的特殊情况,当n=0,n=1,n=链表长度 等不同情况时,该如何处理。
3、考虑head是否需要修改。
- leetcode_19. Remove Nth Node From End of List 删除单链表中的倒数第n个节点,双指针法
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
- Remove Nth Node From End of List 删除链表倒数第N个节点
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- [LeetCode-19] Remove Nth Node From End of List(删除倒数第N个节点)
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- Remove Nth Node From End of List 从链表中删除倒数第N的节点
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- 174.Remove Nth Node From End of List-删除链表中倒数第n个节点(容易题)
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- 【链表&删除倒数第K个节点】Remove Nth Node From End of List
- 删除链表的倒数第n个结点 Remove Nth Node From End of List
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- 5分钟搞定云应用开发
- UGUI自带的颜色渐变效果
- Python高级编程技巧
- 四旋翼初次组装
- Android开源框架Glide的使用-示例应用
- leetcode_19. Remove Nth Node From End of List 删除单链表中的倒数第n个节点,双指针法
- Swift3.0 在OC中调用swift方法 #import "项目名-Swift.h"失效问题
- Extjs4 获取datefield时间格式问题
- 用户定义数据类型
- STL
- python_Ubuntu下安装numpy and matplotlib
- 青蛙跳台阶(java)
- js处理剪贴板的内容
- SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);