码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-04 21:12:31      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   python   c++   

索引:[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


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

标签:leetcode   算法   python   c++   

原文地址:http://blog.csdn.net/hcbbt/article/details/44064205

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!