1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null||head.next==null) return null; if(n==0) return head; int k=0; ListNode slow=head,remove=head; while(head!=null){ if(k>n){ slow=slow.next; } k++; head=head.next; } if(k>n){ slow.next=slow.next.next; } if(k==n){ remove=slow.next; } return remove; } public static ListNode removeNthFromEnd(ListNode head, int n) { ListNode pioneer = head; for (int i=0;i<n-1;i++){ pioneer = pioneer.next; } ListNode pre = new ListNode(-1); ListNode start = pre; pre.next = head; while (pioneer.next!=null){ pioneer = pioneer.next; pre = pre.next; } pre.next = pre.next.next; return start.next; } }
|