待补充(简单)
leecode 19 : 删除链表的倒数第 N 个结点(python3)(中等)
题目:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
常规解法:
踩坑点:这道题主要要考虑的问题是边界处理,当n=1和n=链表长度时要做特殊处理
思路:
1. 获取链表总长度len,如果n==len,返回head.next
2.设置两个指针,如果n==1,将最后一个节点设置为None,反之略过删除节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
list_len = 1
tmp_node = head
while(tmp_node.next):
tmp_node = tmp_node.next
list_len += 1
if n == list_len:
return head.next
front_head = head
behind_node = head
for _ in range(n):
if front_head.next:
front_head = front_head.next
else:
return None
while(front_head.next):
front_head = front_head.next
behind_node = behind_node.next
if n == 1:
behind_node.next = None
else:
behind_node.next = behind_node.next.next
return head
进阶解法:
思路:如果