题目:
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
思路:
使用两个temp指针变量,第一个指针变量指向列表正数第N个元素,第二个指向列表第一个元素,在第一个指针变量的下一个元素不为空时这两个变量同时指向下一个元素,当第一个指针变量指向最后一个元素时,第二个变量指向的就是列表倒数第N个元素。这种思路的原理在于把第一个指针变量当作反过来的列表(元素没有反),然后和第二个指针变量同时指向列表最后一个元素,两个变量的位移量相同,第一个变量就可以指向原列表的表头,第二个列表就可以指向倒数第N个元素了。
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
if head == None or head.next == None:
return None
temp1 = head
temp2 = head
for i in range(n):
temp1 = temp1.next
if temp1 == None: # 删除倒数最后一个也就是第一个元素
return head.next
while temp1.next:
temp1 = temp1.next
temp2 = temp2.next
temp2.next = temp2.next.next
return head