/**
* 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) {
if (head==null || n==0) return null;
if (head.next==null && n==1) return null;
ListNode p = head;
ListNode q = head;
for (int i=0; i<n; i++) {
if (q!=null) q = q.next;
else return head;
}
if (q==null) return head.next;
while (q.next!=null) {
p=p.next;
q=q.next;
}
p.next = p.next.next;
return head;
}
}
没有评论:
发表评论