删除链表的倒数第N个节点
题目
19. 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
- 链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
题解
此题有点难,适合二刷
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.util.ArrayList; import java.util.List;
public class RemoveNthFromEnd {
public static void main(String[] args) { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); ListNode result = removeNthFromEnd(head, 2); while (result != null) { System.out.println(result.val); result = result.next; } }
public static ListNode removeNthFromEnd1(ListNode head, int n) { if (head == null) { return null; } List<Integer> list = new ArrayList<>(); while (head.next != null) { list.add(head.val); head = head.next; } list.add(head.val); list.remove(list.size() - n); ListNode result = null; ListNode item = null; for (Integer integer : list) { if (result == null) { result = new ListNode(integer); item = result; }else{ item.next = new ListNode(integer); item = item.next; } } return result; }
public static ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head); int length = getLength(head); ListNode cur = dummy; for (int i = 1; i < length - n + 1; ++i) { cur = cur.next; } cur.next = cur.next.next; return dummy.next; }
public static int getLength(ListNode head) { int length = 0; while (head != null) { ++length; head = head.next; } return length; } }
|
