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;
    }

      

     
  • 相关阅读:
    统计元音 题解
    C语言合法标识符 题解
    查找最大元素 题解
    java_day05_数组
    java_day4_while循环
    java_day03_if,Switch,三目和for循环
    java_day02_基本运算符和数据类型
    java_day01_注释,变量
    前端_day04_行,块,RGB,行高,overflow
    前端_day03_盒子模型,border,padding,margin
  • 原文地址:https://www.cnblogs.com/focusonoutput/p/13522886.html
Copyright © 2011-2022 走看看