LeetCode:19. 删除链表的倒数第N个节点
1、题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
2、题解
2.1、解法一
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def __init__(self): self.h = None self.num = 0 def add(self, val): if self.h == None: self.h = ListNode(val) self.num += 1 return node = self.h while node.next: node = node.next node.next = ListNode(val) self.num += 1 def get_length(self,head): node = head if head == None: return 0 count = 0 while node: count += 1 node = node.next return count def remove(self,head,n): node = head prev = node count = 0 ret_list = [] while node: print(":",node.val) if count == n: prev.next = node.next self.num -= 1 else: ret_list.append(node.val) prev = node node = node.next count += 1 return ret_list def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ print(self.get_length(head)) ret = self.remove(head,self.get_length(head) -n) return ret