zoukankan      html  css  js  c++  java
  • 删除链表的倒数第N个节点(头部加一个哑结点)

     我的代码:测试用例【1,2】2,  时会报错,无法不能删除第一个指针

    /**
     * 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) return null;
           ListNode node1=head;
           for(int i=0;i<n;i++){
           node1=node1.next;
           }
           if(node1==null||node1.next==null) return null;
    
           ListNode node2=head;
           ListNode node3=null;
           while(node1!=null){
            node1=node1.next;
            node3=node2;
            node2=node2.next;
           }
           node3.next=node3.next.next;
           return head;
        }
    }

    正确方法:在头部加一个哑结点

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);  //  这是加哑结点的方法
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        // Advances first pointer so that the gap between first and second is n nodes apart
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }
        // Move first to the end, maintaining the gap
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }

      

     
  • 相关阅读:
    StartSSL免费证书申请笔记
    CAS实践笔录
    MySQL常用SQL/函数汇总(持续更新)
    Git学习笔记(持续更新)
    Nginx配置性能优化
    OneDrive无法正常登录
    Windows注册表(持续更新)
    Mysql操作笔记(持续更新)
    MySQL 绿色版(zip) 安装
    Ubuntu/Deepin下常用软件汇总(持续更新)
  • 原文地址:https://www.cnblogs.com/focusonoutput/p/13522886.html
Copyright © 2011-2022 走看看