[LeetCode] 19. 刪除鏈表的倒數第N個節點

題目連接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/java

題目描述:

給定一個鏈表,刪除鏈表的倒數第 n 個節點,而且返回鏈表的頭結點。node

示例:

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

當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.

思路:

使用快慢指針,python

快指針先移n個節點spa

接下來,快慢指針一塊兒移動,兩指針之間一直保持n個節點,當快指針到鏈表底了,操做慢指針,刪除要刪除的元素!指針

時間複雜度:\(O(n)\)code


關注個人知乎專欄,瞭解更多解題方法!leetcode

代碼:

# 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:
        if not head:return 
        dummy = ListNode(0)
        dummy.next = head
        fast = dummy
        while n:
            fast = fast.next
            n -= 1
        slow = dummy
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

javarem

/**
 * 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) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;
        for (int i = 0 ; i < n; i ++ ){
            fast = fast.next;
        }
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
        
    }
}
相關文章
相關標籤/搜索