• [LeetCode] 19. 删除链表的倒数第N个节点


    题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

    题目描述:

    给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.
    
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    

    思路:

    使用快慢指针,

    快指针先移n个节点

    接下来,快慢指针一起移动,两指针之间一直保持n个节点,当快指针到链表底了,操作慢指针,删除要删除的元素!

    时间复杂度:(O(n))


    关注我的知乎专栏,了解更多解题方法!

    代码:

    # 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
    

    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) {
            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;
            
        }
    }
    
  • 相关阅读:
    redis的事务不是原子性
    Jenkins持续集成 入门实践
    Docker入门实践
    程序员该有的职业素养
    ubuntu sudoers配置错误
    日志分析工具 Log Parser
    压力测试记录
    Winscp使用sudo user登录
    Linux下通过NFS共享文件夹
    Jexus 5.4.6 on CentOS 6.6
  • 原文地址:https://www.cnblogs.com/powercai/p/10769569.html
Copyright © 2020-2023  润新知