删除链表的倒数第 N 个结点

题目描述:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:利用栈

首先遍历一遍链表,将结点的值放进栈temp里,然后遍历temp,过滤掉第n个结点,剩下的重新组装成链表result,返回result。

备注:进阶的做法可以采用双指针法,待优化。

  1. import java.util.Stack;
  2. public class Solution {
  3. /**
  4. * 方法一:利用栈
  5. * @param head
  6. * @param n
  7. * @return
  8. */
  9. public static ListNode removeNthFromEnd(ListNode head, int n) {
  10. if (head == null) {
  11. return null;
  12. }
  13. Stack<Integer> temp = new Stack<>();
  14. while (head != null) {
  15. temp.push(head.val);
  16. head = head.next;
  17. }
  18. Stack<Integer> result = new Stack<>();
  19. int count = 1;
  20. boolean findN = false;
  21. while (!temp.isEmpty()) {
  22. if (count == n) {
  23. temp.pop();
  24. findN = true;
  25. count++;
  26. continue;
  27. }
  28. result.push(temp.pop());
  29. count++;
  30. }
  31. if (!findN) {
  32. return null;
  33. }
  34. ListNode resultNode = new ListNode(-1);
  35. ListNode next = resultNode;
  36. while (!result.isEmpty()) {
  37. next.next = new ListNode(result.pop());
  38. next = next.next;
  39. }
  40. return resultNode.next;
  41. }
  42. public static void main(String[] args) {
  43. ListNode root = new ListNode(1);
  44. root.next = new ListNode(2);
  45. root.next.next = new ListNode(3);
  46. root.next.next.next = new ListNode(4);
  47. root.next.next.next.next = new ListNode(5);
  48. root = removeNthFromEnd(root, 2);
  49. while (root != null) {
  50. System.out.print(root.val + "->");
  51. root = root.next;
  52. }
  53. }
  54. }
  55. class ListNode {
  56. int val;
  57. ListNode next;
  58. ListNode() {
  59. }
  60. ListNode(int val) {
  61. this.val = val;
  62. }
  63. ListNode(int val, ListNode next) {
  64. this.val = val;
  65. this.next = next;
  66. }
  67. }

【每日寄语】你今天的努力,是幸运的伏笔,当下的付出,是明日的花开。