diff --git a/src/main/java/com/cool/hot100/linkedlist/Num19.java b/src/main/java/com/cool/hot100/linkedlist/Num19.java new file mode 100644 index 0000000..970fff6 --- /dev/null +++ b/src/main/java/com/cool/hot100/linkedlist/Num19.java @@ -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 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+10){ + 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); + } +}