这道题还可以用递归法,你想到了吗?
LeetCode链接:19. 删除链表的倒数第 N 个结点
1.题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:

1 2
| 输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
|
示例 2:
示例 3:
提示:
- 链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
2.题解
2.1 暴力解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { int length = getLength(head);
int index = length - n;
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy; for (int i = 0; i < index; i++) { pre = pre.next; }
pre.next = pre.next.next;
return dummy.next; }
public int getLength(ListNode head) { int length = 0; while (head != null) { length++; head = head.next; } return length; } }
|
2.2 双指针- 暴力解法优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode first = dummy, second = dummy; for (int i = 0; i < n; i++) { first = first.next; } while (first.next != null) { first = first.next; second = second.next; } second.next = second.next.next; return dummy.next; } }
|
2.3 递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { int count = 0;
public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) return null;
head.next = removeNthFromEnd(head.next, n); count++; return count == n ? head.next : head; } }
|
2.4 借助栈
- 我们知道递归的本质就是栈,因此我们也可以使用栈来解决这道题目
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode newHead = new ListNode(0,head); Stack<ListNode> stack = new Stack<>(); ListNode cur = newHead; while(cur != null){ stack.push(cur); cur = cur.next; }
for(int i=0;i<n;i++){ stack.pop(); } ListNode pre = stack.pop(); pre.next = pre.next.next; return newHead.next; } }
|