思路
你选用何种方法解题?遍历,先算出整体的长度,再利用两个极端情况考虑,剩下的就是遍历
解题过程
这些方法具体怎么运用?主要是这里 if(num ==0){
head =null;
return head;
}
if(num+1==n){
head = head.next;
return head;
}
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
int i = 0;
ListNode head_temp = head;
ListNode head_temp1 = head;
int num =0;
while(head_temp1.next!=null){
num++;
head_temp1 = head_temp1.next;
}
if(num ==0){
head =null;
return head;
}
if(num+1==n){
head = head.next;
return head;
}
for(;i<num-n;i++){
head_temp = head_temp.next;
}
ListNode temp = head_temp.next;
head_temp.next = temp.next;
return head;
}

被折叠的 条评论
为什么被折叠?



