题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
解题思路
设置两个指针,让第一个指针先走n步,然后第二个指针再一起走,最后第一个指针遍历完后第二个指针指的节点就为要删除的结点。
代码
# 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
"""
p=head
q=head
a = head
length = 0
#先让p走n步
for i in range(n):
length = length+1
p = p.next
while p:
length = length + 1
p = p.next
a = q
q = q.next
if length==1 or length==n:
return head.next
else:
a.next = a.next.next
return head
aa = [1,2]
a = ListNode(-1)
cur_a = a
for i in aa:
cur_a.next = ListNode(i)
cur_a = cur_a.next
head = a.next
S= Solution()
aaa = S.removeNthFromEnd(head, 2)
print(aaa.val)