24.8.22 LeetCode Hot100 linkedList
This commit is contained in:
parent
ba8f4e0ecb
commit
c0bdbfe0db
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue