方法一: 双指针容易点。
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 // Write your solution here 4 if (head == null) { 5 return head; 6 } 7 8 if (n > getNum(head)) { 9 return head; 10 } 11 12 ListNode dummy = new ListNode(0); 13 dummy.next = head; 14 ListNode fast = dummy, slow = dummy; 15 for (int i = 0; i <= n; i++) { 16 fast = fast.next; 17 } 18 19 while (fast != null) { 20 fast = fast.next; 21 slow = slow.next; 22 } 23 slow.next = slow.next.next; 24 return dummy.next; 25 } 26 27 private int getNum(ListNode head) { 28 int count = 0; 29 while (head != null) { 30 count++; 31 head = head.next; 32 } 33 return count; 34 } 35 }
方法二: 数个数
1 public ListNode removeNthNode(ListNode head, int n) { 2 // Should using dummy node here because n may remove the head node.So we must keep the head. 3 if (head == null || n == 0) { 4 return head; 5 } 6 7 ListNode dummy = new ListNode(0); 8 dummy.next = head; 9 ListNode cur = dummy; 10 11 ListNode fast = head; 12 ListNode slow = head; 13 14 // Firstly, count the length of the linked list 15 int len = 1; 16 while(fast.next != null && fast.next.next != null) { 17 fast = fast.next.next; 18 slow = slow.next; 19 len++; 20 } 21 // 1 2 3 4 5 6 7 8 null , for n = 5 22 // dummy n 23 if (fast.next == null) { 24 len = 2 * len - 1; 25 } else if (fast.next.next == null) { 26 len = 2 * len; 27 } 28 29 // Calculate the difference of length: 8 - 5 = 3 30 int pos = len - n; 31 32 // If we use the dummy node, then the i must start from i = 0; 33 for (int i = 0; i < pos; i++) { 34 cur = cur.next; 35 } 36 // cur points to 3, we need to delete 4 37 cur.next = cur.next.next; 38 return dummy.next; 39 }