/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/classSolution{public ListNode removeNthFromEnd(ListNode head,int n){
ListNode ans=newListNode(0);
ans.next=head;int i=0;
ListNode first = head;while(first != null){
i++;
first=first.next;}
first = ans;for(int j=0;j<i-n;j++){
first=first.next;}
first.next=first.next.next;return ans.next;}}
解法二:官方说这个是扫描了一遍,可是我觉得好像不止一遍吧。。。但是时间复杂度确实很低。
public ListNode removeNthFromEnd(ListNode head,int n){
ListNode dummy =newListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;// Advances first pointer so that the gap between first and second is n nodes apartfor(int i =1; i <= n +1; i++){
first = first.next;}// Move first to the end, maintaining the gapwhile(first != null){
first = first.next;
second = second.next;}
second.next = second.next.next;return dummy.next;}
作者:LeetCode
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-by-l/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。