常规解法:用栈,空间复杂度和时间复杂度都是O(n),不满足题目要求
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
if (head == null || n == 0) {
return head;
}
ListNode pre = head;
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode cur = null;
while (!stack.isEmpty()) {
cur = stack.pop();
if (--n == 0) {
if (!stack.isEmpty()) {
stack.pop().next = cur.next;
return pre;
} else {
return pre.next;
}
}
}
return pre;
}
}
第二种解法:快慢指针
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
if (head == null || n == 0) {
return head;
}
ListNode fast = new ListNode(-1);
fast.next = head;
while (n > 0) {
fast = fast.next;
n--;
}
ListNode slow = new ListNode(-1);
slow.next = head;
//删除的是头节点
if (fast.next == null) {
return head.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}