zoukankan      html  css  js  c++  java
  • LeetCode19- Remove Nth Node From End of List-Medium

    删除链表中倒数第n个结点

    题目:LeetCode19

    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?

    思路:

    题目要求one pass,即只遍历一遍链表并完成删除操作。

    如果删除倒数第n个结点,需要定位到该结点的前一个结点。

    两种情况,1)删除的结点是头结点;2)删除的结点非头结点

    首先:定义一个快指针,从链表头部走n步。如果此时已经指向null,说明要删除的结点是该链表的头结点,则返回head.next。即case 1。

    case 2: 如果快指针此时没有指向null, 定义一个慢指针指向头结点,快慢指针同时向后移动,当快指针指向最后一个结点时,慢指针指向被删除结点的前一个。

    操作慢指针,删除倒数第n个结点(slow.next = slow.next.next)。(注意:这里慢指针和快指针至少相差1,所以当快指针指向最后一个结点,slow.next.next 不会nullpointer异常。)

    代码:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast = head;
            
            while (n > 0) {
                fast = fast.next;
                n--;
            }
            
            if (fast == null) {
                return head.next;
            }
            
            ListNode slow = head;
            while (fast.next != null) {
                slow = slow.next;
                fast = fast.next;
            }
            
            slow.next = slow.next.next;
            return head;
        }
    }
  • 相关阅读:
    <s:property>的用法(jsp获取action中的值或者方法)
    struts2 Action获取表单数据
    form标签中id和name属性的区别
    button和submit区别
    hibernate could not resolve property
    Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyExce
    宏定义#define和内联函数inline的区别
    线程绑定cpu
    posix系统线程调度-设置线程优先级
    std::lock_guard和std::unique_lock的区别
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/12985255.html
Copyright © 2011-2022 走看看