明天要面试,好紧张,我啥也不会。我还在复习写过的博客。
今天没空写题了,但为了每天都写题,迅速写道水题。
题目
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
代码
/**
* 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; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)
return null;
ListNode a=head;
ListNode b=head;
for(int i=0;i<n;i++){
a=a.next;
}
//a走到底为Null了,说明要删除的是头结点
if(a==null){
return head.next;
}
while(a.next!=null){
b=b.next;
a=a.next;
}
b.next=b.next.next;
return head;
}
}
复杂度
时间复杂度:O(L),其中 L 是链表的长度。
空间复杂度:O(1)。