18 leetcode - Remove Nth Node From End of List
来源:互联网 发布:汉字笔画笔顺软件 编辑:程序博客网 时间:2024/06/05 11:34
指针追赶。
设两个指针,一个先走n步,然后同时走。
#!/usr/bin/python# -*- coding: utf-8 -*-'''英文:Given a linked list, remove the nth node from the end of list and return its head.中文:移除倒数第n个节点举例: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.'''# 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 """ first = head second = head while n: first = first.next n -= 1 if first == None:#已经到了结尾了 if n > 0: #说明n已经超过了链表的长度,直接返回头节点即可 return head else:#恰好删除头节点 return head.next #删除的节点在链表中间 while first.next: first = first.next second = second.next #second.next为倒数第n个节点,让second.next = second.next.next就跳过了倒数第n个节点 second.next = second.next.next return head
0 0
- 18 leetcode - Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- c++修饰符类型
- C++ std::list实现大整数加法运算
- 第三节.Redis的使用
- bzoj 4295 [PA2015]Hazard 单调队列
- 计算机视觉基础(一)——左右手坐标系转换时R和T的具体形式分析
- 18 leetcode - Remove Nth Node From End of List
- [论文复现]Detecting Text in Natural Image with Connectionist Text Proposal Network
- MySQL学习
- 华为手机不打印崩溃日志log问题解决
- storm集群搭建
- Android自定义柱状图,带有标注和左右滑动效果
- centos6.x安装KVM
- iOS开发——XML/JSON数据解析
- SharedPreferences存储数据的使用方法