[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


019.Remove_Nth_Node_From_End_of_List (Easy)

链接

题目:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
代码(github):https://github.com/illuz/leetcode

题意

删除一个单向链表的倒数第 N 个节点。

分析

  1. 直接模拟,先算出节点数,再找到节点删除
  2. 用两个指针,一个先走 N 步,然后再一起走。

这里用 C++ 实现第一种, 用 Python 实现第二种。
Java 的话和 C++/Python 差不多,不写出来了。

代码

C++:

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
		if (n == 0)
			return head;
		// count the node number
		int num = 0;
		ListNode *cur = head;
		while (cur != NULL) {
			cur = cur->next;
			num++;
		}
		if (num == n) {
			// remove first node
			ListNode *ret = head->next;
			delete head;
			return ret;
		} else {
			// remove (cnt-n)th node
			int m = num - n - 1;
			cur = head;
			while (m--)
				cur = cur->next;
			ListNode *rem = cur->next;
			cur->next = cur->next->next;
			delete rem;
			return head;
		}
    }
};



Python:

class Solution:
    # @return a ListNode
    def removeNthFromEnd(self, head, n):
        dummy = ListNode(0)
        dummy.next = head
        p, q = dummy, dummy
        
        # first 'q' go n step
        for i in range(n):
            q = q.next

        # q & p
        while q.next:
            p = p.next
            q = q.next

        rec = p.next
        p.next = rec.next
        del rec
        return dummy.next


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值