解题思路:一开始我的做法是先遍历一遍取得长度,然后长度减去n就知道要删除正着数第几个元素,结果没注意到题目要求one pass结果不行。那就只能用两个指针,一个快指针先走n步,一个慢指针从头开始走,这样当快指针走到尾部的时候,慢指针所指的就是要删除元素的前一个元素。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if( head==null ) return null;
ListNode p=head;
ListNode q=head;
for(int i=0;i<n;i++){
q=q.next;
}
if(q==null){
head=head.next;
return head;
}
while(q.next!=null){
p=p.next;
q=q.next;
}
p.next=p.next.next;
return head;
}
}
官方答案如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null) return null;
final ListNode _head = new ListNode(0);
_head.next = head;
ListNode fast = _head;
ListNode slow = _head;
for(int i = 0; i< n ; i++) fast = fast.next;
while(fast != null && fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return _head.next;
}
}
按照下面这种思路在head节点前先new一个节点其实意思和我们判断一下删除的节点是不是head节点是一个道理的