LeetCode #19 Remove Nth Node From End of List 刪除鏈表的倒數(shù)第N個(gè)節(jié)點(diǎn)

19 Remove Nth Node From End of List 刪除鏈表的倒數(shù)第N個(gè)節(jié)點(diǎn)

Description:
Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

題目描述:
給定一個(gè)鏈表,刪除鏈表的倒數(shù)第 n 個(gè)節(jié)點(diǎn),并且返回鏈表的頭結(jié)點(diǎn)。

示例 :

給定一個(gè)鏈表: 1->2->3->4->5, 和 n = 2.

當(dāng)刪除了倒數(shù)第二個(gè)節(jié)點(diǎn)后,鏈表變?yōu)?1->2->3->5.

說明:

給定的 n 保證是有效的。

進(jìn)階:

你能嘗試使用一趟掃描實(shí)現(xiàn)嗎?

思路:

此題為 408原題

  1. 先遍歷一次鏈表獲取長(zhǎng)度, 找到倒數(shù)第 n個(gè)結(jié)點(diǎn)的位置并移除, 需要遍歷兩次鏈表
  2. 設(shè)置快慢指針, 快指針先移動(dòng) n個(gè)結(jié)點(diǎn), 然后快慢指針同步移動(dòng), 移除當(dāng)快指針為空時(shí)慢指針位置的結(jié)點(diǎn)即可, 只需要遍歷一次鏈表
    時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)

代碼:
C++:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) 
    {
        if (!head or !head -> next) return nullptr;
        ListNode *fast = head, *slow = head;
        for (int i = 0; i < n; i++) fast = fast -> next;
        if (!fast) return head -> next;
        while (fast -> next) 
        {
            fast = fast -> next;
            slow = slow -> next;
        }
        slow -> next = slow -> next -> next;
        return head;
    }
};

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || head.next == null) return null;
        ListNode fast = head, slow = head;
        for (int i = 0; i < n; i++) fast = fast.next;
        if (fast == null) return head.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}

Python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head
        p = q = dummy
        for i in range(n + 1):
            p = p.next
        while p:
            p, q = p.next, q.next
        q.next = q.next.next
        return dummy.next
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容