编程语言
首页 > 编程语言> > 算法打卡Week8

算法打卡Week8

作者:互联网

题目:删除链表的倒数第 N 个结点
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

例一:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

例二:

输入:head = [1], n = 1
输出:[]

例三

输入:head = [1,2], n = 1
输出:[1]

思路:
我们采用双指针的方式,快指针listNode_fast和慢指针listNode_slow同时指向dummy节点,当listNode_fast指向NULL时候,中间夹着n个元素时候,删除listNode_slow下一节点,即可
1、设置虚拟节点dummy,指向head→解决要删除头节点的情况(eg:[1],1);
2、指针listNode_fast和listNode_slow分别指向head和dummy;
3、移动listNode_fast,直到两指针相隔n个元素;
4、同时移动listNode_fast和listNode_slow,直到listNode_fast指向NULL;
5、将listNode_slow.next指向下下节点。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0, head)
        listNode_slow = dummy
        listNode_fast = head
        for _ in range(n):
        	listNode_fast = lsitNode_fast.next
        
        while listNode_fast:
        	listNode_fast = listNode_fast.next
        	listNode_slow = listNode_slow.next
        
        listNode_slow.next = listNode_slow.next.next
        return dummy.next

标签:dummy,head,slow,listNode,fast,next,Week8,算法,打卡
来源: https://blog.csdn.net/i_lickey/article/details/116705000