【问题描述】
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
【思路】
【思路1】
两趟扫描,第一趟求List长度,将从后面删除转为从前删除len-n+1
注意:在第二趟拼接时,i=0,i++判断temp是否为null较方便,不容易溢出
/**
* 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) {
if (head == null) {
return null;
}
ListNode temp = head;
int count = 1;
while (temp.next != null) {
count++;
temp = temp.next;
}
if ((count - n + 1) == 1) {
return head.next;
}
temp = head;
int i = 0;
while (temp != null) {
i++;
if (i == count - n) {
temp.next = temp.next.next;
}
temp = temp.next;
}
return head;
}
}