@author: ZZQ
@software: PyCharm
@file: removeNthFromEnd.py
@time: 2018/9/26 21:56
说明:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明: 给定的 n 保证是有效的。
进阶: 你能尝试使用一趟扫描实现吗?
思路: 双指针p和q,一个指向头结点,一个指向第k个节点,然后同时向下移,当q的下一个节点为空时,p所指就是倒数第k个节点。
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution():
def __init__(self):
pass
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
p = head
q = head
for i in range(1, n+1):
if q.next is None and i == n:
head = head.next
return head
q = q.next
while q.next is not None:
q = q.next
p = p.next
p.next = p.next.next
return head
if __name__ == "__main__":
answer = Solution()
a = ListNode(1)
p = a
p.next = ListNode(2)
p = p.next
p.next = ListNode(3)
p = p.next
p.next = ListNode(4)
p = p.next
p.next = ListNode(5)
l3 = answer.removeNthFromEnd(a, 5)
while l3 is not None:
print l3.val
l3 = l3.next