链表常见解法:
使用前后指针, 前指针遍历完时后指针指向删除节点;

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
|
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy=new ListNode(0,head); ListNode back = dummy; ListNode front = head; for(int i=0;i<n;i++){ front=front.next; } while(front!=null){ front=front.next; back=back.next; } back.next=back.next.next; return dummy.next; } }
|