【LEETCODE】19-Remove Nth Node From End of List
2015-12-21 15:05
579 查看
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.
参考: http://yucoding.blogspot.com/2013/04/leetcode-question-82-remove-nth-node.html
题意:
给一个linked list和数字n,移除倒数第n个数,返回head
思路:
两个指针p,q同时从head出发
q先移动n步
然后p,q同时移动
当q到达end时,p.next=p.next.next即可
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.
参考: http://yucoding.blogspot.com/2013/04/leetcode-question-82-remove-nth-node.html
题意:
给一个linked list和数字n,移除倒数第n个数,返回head
思路:
两个指针p,q同时从head出发
q先移动n步
然后p,q同时移动
当q到达end时,p.next=p.next.next即可
# 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 """ head1=ListNode(0) #增加0点 head1.next=head head=head1 p=q=head for i in range(n+1): #因为多了一个0点,所以q要走n+1步 q=q.next while q: #因为多了一个0点,所以是判断q而不是q.next,这样p才可以也多走一步 p=p.next q=q.next p.next=p.next.next return head.next
相关文章推荐
- 【实践】express搭建nodeJS中间层(一)
- 高速理解掌握node.js 字符编码,确码过程 以及base64编解码原理
- NodeJS | Js 对象 module.exports -笔记(1)
- nodejs addon如何生成xcode工程
- Node.js 事件循环
- Node.js 回调函数
- Node Js 学习第一天
- LeetCode Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 深入浅析NodeJs并发异步的回调处理
- Why The Hell Would I Use Node.js? A Case-by-Case Tutorial
- Node Eviction due to OLOGGERD High CPU
- nodejs搞服务器
- nodejs入门三
- nodejs入门二
- windows下搭建node.js及npm的工作环境
- LeetCode - Reverse Nodes in k-Group
- LeetCode - Swap Nodes in Pairs
- *LeetCode Remove Nth Node From End of List 双指针
- 深入浅析NodeJs并发异步的回调处理