题目链接

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

题目描述

image.png

实现代码

题目比较简单,直接上实现代码:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode removeNthFromEnd(ListNode head, int n) {
  13. ListNode dummy = new ListNode(0, head);
  14. ListNode first = head;
  15. ListNode second = dummy;
  16. for (int i = 0; i < n; ++i) {
  17. first = first.next;
  18. }
  19. while (first != null) {
  20. first = first.next;
  21. second = second.next;
  22. }
  23. second.next = second.next.next;
  24. ListNode ans = dummy.next;
  25. return ans;
  26. }
  27. }