https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
解法:
package leetcode2;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* 2021/3/10 11:15
*
* @Author ayue
*/
public class Solution19 {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {//map存放各位置节点,找到被删除的节点
if (head.next == null) {
return null;
}
Map<Integer, ListNode> map = new HashMap<Integer, ListNode>();
ListNode cur = head;
while (cur != null) {
map.put(map.size(), cur);
cur = cur.next;
}
if (map.size() == n) {
return map.get(1);
} else {
map.get(map.size() - n - 1).next = map.get(map.size() - n).next;
return map.get(0);
}
}
public ListNode removeNthFromEnd2(ListNode head, int n) {//两遍循环找到被删除的节点
int len = 0;
ListNode cur = head;
while (cur != null) {
len++;
cur = cur.next;
}
if (len == n) {
return head.next;
}
cur = head;
for (int i = 0; i < len - n - 1; ++i) {
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
public ListNode removeNthFromEnd3(ListNode head, int n) {//栈先进后出寻找被删除的节点
Stack<ListNode> stack = new Stack<ListNode>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
if (stack.size() == n) {
return head.next;
}
for (int i = 0; i < n; ++i) {
stack.pop();
}
cur = stack.peek();
cur.next = cur.next.next;
return head;
}
public ListNode removeNthFromEnd4(ListNode head, int n) {//快慢指针寻找被删除的节点
ListNode first = head;
ListNode second = head;
for (int i = 0; i < n; ++i) {
first = first.next;
}
if (first == null) {
return head.next;
}
while (first.next != null) {
second = second.next;
first = first.next;
}
second.next = second.next.next;
return head;
}
public static void main(String[] args) {
Solution19 solution19 = new Solution19();
ListNode listNode = solution19.new ListNode(1);
// listNode.next = solution19.new ListNode(2);
// listNode.next.next = solution19.new ListNode(3);
// listNode.next.next.next = solution19.new ListNode(4);
// listNode.next.next.next.next = solution19.new ListNode(5);
ListNode cur = solution19.removeNthFromEnd4(listNode, 1);
while (cur != null) {
System.out.println(cur.val);
cur = cur.next;
}
}
}