zoukankan      html  css  js  c++  java
  • 019 Remove Nth Node From End of List 删除链表的倒数第N个节点

    给定一个链表,删除链表的倒数第 n 个节点并返回头结点。
    例如,
    给定一个链表: 1->2->3->4->5, 并且 n = 2.
    当删除了倒数第二个节点后链表变成了 1->2->3->5.
    详见:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

    思路:设置两个指针first跟second。first指针先移动n步,若此时first指针为空,则表示要删除的是头节点,此时直接返回head->next即可。如果first指针不为空,则将两个指针一起移动,直到first指针指向最后一个节点,令second->next=second->next->next即可删除第你n个节点。

    实现语言: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 first=head,second=head;
            for(int i=0;i<n;++i){
                first=first.next;
            }
            if(first==null){
                return head.next;
            }
            while(first.next!=null){
                first=first.next;
                second=second.next;
            }
            second.next=second.next.next;
            return head;
        }
    }
    

     参考:https://blog.csdn.net/yao_wust/article/details/41242805

  • 相关阅读:
    list集合对象日期排序
    Mongodb模糊,or,and查询和日期查询
    单例模式
    代理模式
    抽象工厂模式
    java 除数运算获取两位小数
    html5 canvas 使用总结
    @MockBean 注解后 bean成员对象为 null?
    Java8 BiFunction 简单用用
    如何正确安装Ubuntu
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8684844.html
Copyright © 2011-2022 走看看