[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-04-02 08:42:37 閱讀次數(shù):2643次
索引:[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
題意:
刪除1個(gè)單向鏈表的倒數(shù)第 N 個(gè)節(jié)點(diǎn)。
分析:
- 直接摹擬,先算出節(jié)點(diǎn)數(shù),再找到節(jié)點(diǎn)刪除
- 用兩個(gè)指針,1個(gè)先走 N 步,然后再1起走。
這里用 C++ 實(shí)現(xiàn)第1種, 用 Python 實(shí)現(xiàn)第2種。
Java 的話和 C++/Python 差不多,不寫出來(lái)了。
代碼:
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
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)