leetcode 19 删除链表的倒数第N个节点 (c++和python)

题目描述: 

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

解题思路:

 快慢指针法。

1)先移动快节点n次,使得上面例子:fast将指向2;

2)再一起移动,上面例子:fast将指向5,slow将指向3,即slow指向的是要删除节点的前一个节点。

C++代码:

执行用时:8 ms, 在所有 C++ 提交中击败了26.03%的用户

内存消耗:10.4 MB, 在所有 C++ 提交中击败了74.75%的用户

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *myHead = new ListNode(0); // 定义一个头结点,存放的是0
        myHead->next = head;

        // 双指针,一前一后,相差n+1个位置,后面的指向末尾时,则前一个指针指向的就是要删除节点的前一个节点
        ListNode* slow = myHead;  // 
        ListNode* fast = myHead;

        // 先移动n次后节点,在上面例子:fast将指向2
        for (int i = 0; i < n; i++)
        {
            fast = fast->next;
        }
        // 同时移动slow和fast,slow指针指向的就是要删除节点的前一个节点
        if (fast == nullptr) return nullptr;
        while(fast->next != nullptr)
        {
            slow = slow->next;
            fast = fast->next;
        }

        // 应该删除的节点是:slow
        ListNode* t = slow->next; 
        slow->next = slow->next->next;
        delete t;
        t = nullptr;

        return myHead->next;

    }
};

python代码:

执行用时:16 ms, 在所有 Python 提交中击败了87.66%的用户

内存消耗:13.3 MB, 在所有 Python 提交中击败了5.58%的用户

# 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
        """
        myHead = ListNode(0)
        myHead.next = head
        fast = myHead
        slow = myHead

        # 先移动快指针n次
        for i in range(n):
            fast = fast.next
        
        # 一起移动
        if fast is None: return None 
        while fast.next is not None:
            fast = fast.next
            slow = slow.next

        # 删除
        t = slow.next
        slow.next = slow.next.next
        del t

        return myHead.next
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值