您的位置:首页 > Web前端 > Node.js

【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即可





# 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: