24.8.22 LeetCode Hot100 linkedList

This commit is contained in:
Cool 2024-08-22 23:22:29 +08:00
parent ba8f4e0ecb
commit c0bdbfe0db
1 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,63 @@
package com.cool.hot100.linkedlist;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class Num19 {
/**
* Date 2024/8/22
* DayNumber 2
* Hard 2
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
// Ans1 Space O(n)
// List<ListNode> list=new ArrayList<>();
// ListNode node=head;
// while (node!=null){
// list.add(node);
// node=node.next;
// }
// int index=list.size()-n;
// if(index==0){
// return list.size()>1?list.get(1):null;
// }
// if(index==list.size()){
// list.get(list.size()-1).next=null;
// return list.get(0);
// }
// ListNode temp=null;
// if(index+1<list.size()){
// temp=list.get(index+1);
// }
// list.get(index-1).next=temp;
// return list.get(0);
// Ans2
if(head==null) return null;
ListNode fast=head;
ListNode slow=null;
while (n>0){
fast=fast.next;
n--;
}
while (fast!=null){
fast=fast.next;
slow=slow==null?head:slow.next;
}
if (slow == null) {
return head.next;
}
slow.next=slow.next.next;
return head;
}
@Test
public void test() {
ListNode node = new ListNode(1);
ListNode node1 = new ListNode(2, node);
removeNthFromEnd(node1, 1);
}
}