方法一
- 首先求出整个链表的长度;
- 如果链表长度为给出的指定的位置,表明要删除的头结点;
- 然后用长度和给出的指定的位置求出要删除的位置;
public ListNode removeNthFromEnd(int n) {
int nums = 0;
ListNode next = head;
while (next != null) {
nums++;
next = next.next;
}
if (n == nums) {
return head.next;
}
int tar = nums - n - 1;
int i = 0;
ListNode front = head;
ListNode behind = head.next;
while (i < tar) {
front = behind;
behind = behind.next;
i++;
}
front.next = behind.next;
return head;
}
方法二:双指针法
- 先让尾指针走n个位置;
- 然后将尾指针和头指针一起移动,直到尾指针指向最后一个结点;
- 这时头指针指向的结点的下一个结点就是要删除的结点;
public ListNode removeNthFromEnd(int n) {
ListNode front = head;
ListNode behind = head;
for (int i = 0; i < n; i++) {
behind = behind.next;
}
if (behind == null) {
return head.next;
}
while (behind.next != null) {
behind = behind.next;
front = front.next;
}
front.next = front.next.next;
return head;
}