{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "a4a05fa8ae2043028026f1aeb8d31b26", "keywords": "链表,双指针", "title": "删除链表的倒数第 N 个结点", "desc": [ { "content": "\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]

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "java" } ], "prepared": [ [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ] ], "template": { "content": "public class ListNode {\n\tint val;\n\tListNode next;\n\tListNode() {\n\t}\n\tListNode(int val) {\n\t\tthis.val = val;\n\t}\n\tListNode(int val, ListNode next) {\n\t\tthis.val = val;\n\t\tthis.next = next;\n\t}\n}\nclass Solution {\n\tpublic ListNode removeNthFromEnd(ListNode head, int n) {\n\t\tListNode v = new ListNode(0, head);\n\t\tListNode handle = v;\n\t\tList index = new ArrayList<>();\n\t\twhile (v != null) {\n\t\t\tindex.add(v);\n\t\t\tv = v.next;\n\t\t}\n\t\tint pre = index.size() - n - 1;\n\t\tint next = index.size() - n + 1;\n\t\tindex.get(pre).next = next >= 0 && next < index.size() ? index.get(next) : null;\n\t\treturn handle.next;\n\t}\n}", "language": "java" }, "node_id": "dailycode-ccc2cd1afb9b4c05abec6e80d581bfd2", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600469818" }