先计算链表总长度 len, 再减去 输入 n, 得到的就是要删除Node的位置,缺点无法 one pass, 时间: 16ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len = getLength(head);
if(len==0 || (len==1 && n<=1) ||len<n) return null;
if(len==n){
head = head.next;
}
ListNode pre = head;
ListNode cur = head;
for(int i=0;i<len-n;i++){
pre = cur;
cur = cur.next;
}
pre.next = cur.next;
return head;
}
public int getLength(ListNode head){
int length = 0;
ListNode tmpNode = head;
while(tmpNode!=null){
length++;
tmpNode = tmpNode.next;
}
return length;
}
}
要实现 one pass 利用双指针,两个指针之间相差 输入 n, 那么当第一个指针知道末尾时,前一个指针就在倒数n 的位置, 16ms
/**
* 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 pre = head;
ListNode cur = head;
for(int i=0;i<n;i++) {
pre= pre.next;
}
if(q == null) {
head = head.next;
return head;
}
while(pre.next != null) {
cur = cur.next;
pre = pre.next;
}
cur.next = cur.next.next;
return head;
}
}