您的位置:首页 > 其它

leetcode之-题19

2016-02-18 14:20 302 查看

题目

19. Remove Nth Node From End of List


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-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点

注意:可能会出现只有1个节点,同时n=1的情况,这时指针没有后继节点

python代码

# 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
"""
"""
采用双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点
"""
p = head
q = head
Ppre = None
for x in xrange(0, n-1):
q = q.next
while q.next is not None:
Ppre = p
p = p.next
q = q.next
# 出现[1],n=1的情况下,Ppre依然为None
if Ppre == None:
head = p.next
else:
Ppre.next = p.next
return head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: