末日搭车指南
面向人生编程

导航

 

 

 我的代码:测试用例【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;
}

 

  

 

 
posted on 2020-08-18 12:44  末日搭车指南  阅读(174)  评论(0)    收藏  举报