Remove Nth Node From End of List
给一个linked list和一个数, 删除list后边n个node. 这个用双指针经典做法
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 |
/** * 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 pre = head; ListNode cur = head; ListNode next = head; for(int i = 0 ; i < n ; i++){ next = next.next; } while(next != null) { pre = cur; cur = cur.next; next = next.next; } if(cur == head && next == null) head = head.next; pre.next = cur.next; return head; } } |