[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++
发布时间:2020-12-13 20:04:35 所属栏目:PHP教程 来源:网络整理
导读:索引:[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):htt
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) 019.Remove_Nth_Node_From_End_of_List (Easy)链接:题目:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ 题意:删除1个单向链表的倒数第 N 个节点。 分析:
这里用 C++ 实现第1种, 用 Python 实现第2种。 代码: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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |