题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
if (head == null) {
return null;
}
Stack<ListNode> st = new Stack<>();
ListNode tmp = head;
do {
st.push(tmp);
tmp = tmp.next;
} while (tmp != null);
for (int i = 0; i < n; i++) {
tmp = st.pop();
}
if (st.empty()) {
return tmp.next;
}
ListNode lastNode = st.pop();
lastNode.next = tmp.next;
return head;
}
}
查看1道真题和解析