数据结构算法操作试题(C++/Python)——删除链表的倒数第N个节点

文章目录

    • 1. 题目
    • 2. 解答


数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/comments/

数据结构算法操作试题(C++/Python)——删除链表的倒数第N个节点_第1张图片

2. 解答

使用双指针p1,p2 ,p1先走n 步长,然后p1,p2同时开始,p1为空的时候结束
python:28 ms,10.9 MB

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        first_p = second_p = head
        cnt = 0
        while first_p != None:
            if cnt <= n:
                first_p = first_p.next
                cnt += 1
                continue
            first_p = first_p.next
            second_p = second_p.next
            cnt += 1
        if cnt == 1:
            return None
        elif cnt == n:
            return head.next
        else:
            second_p.next = second_p.next.next
            return head

其他方法看 leetcode 链接 评论区~

你可能感兴趣的:(#,1.1,Python,#,1.8,C++,#,2.13,数据结构,Data,Structure,6.,笔试,AND,面试,leetcode,删除链表的倒数第N个节点,remove,nth,node,for,end,of,list)