注意的地方:1、使用双指针操作,当第二个指针到尾部时,第一个指针的位置就是要删除位置的前一位
2、注意head节点的删除,如果删除head,直接使head返回null;
/**
* 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) {
ListNode p1 = head;
ListNode pre = head;
int pos = 0;
if (head.equals(null)|| n==0)
return head;
if(head.next==null && n==1)
return null;
for(int i = 0;i<n;i++){
p1 = p1.next;
}
if(p1==null){ //如果当p1走到指定位置时,发现超过了链的长度,那么p1一定是null,此时,删除的是head;
head = head.next;
pre = null ;
return head;
}
while(p1.next!=null){
p1 = p1.next;
pre = pre.next;
}
pre.next = pre.next.next;
return head;
}
}
改进方法:在head之前新建一个节点,也就是新建一个头结点永远不会删除的链表-----原链表从head.next开始!
public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) return null; ListNode headCount = new ListNode(0); headCount.next = head; head = headCount; //在head之前新建一个节点,这个节点的值为0;这样的话,新的链表的head是这个新加的节点
//而不是原来的head,这样就可以不用考虑头结点的处理了 ListNode tmp = head, slow = head.next, fast = head.next; int count = 1; while (count < n) { count++; fast = fast.next; } while (fast.next != null) { fast = fast.next; slow = slow.next; tmp = tmp.next; } tmp.next = slow.next; return head.next; }