• 删除链表的倒数第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;
    }

      

     
  • 相关阅读:
    HOWTO get multiple value from the same name checkbox elements or radiobution elements
    你家有几台电脑
    *qian翻
    nginx 域名绑定
    linode设置汇总
    how to relize 301 redirect on bottle
    Nginx禁止未在服务器绑定的域名访问
    linode设置汇总
    sogouq免费企邮
    linode设置汇总
  • 原文地址:https://www.cnblogs.com/focusonoutput/p/13522886.html
Copyright © 2020-2023  润新知