给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
两种方式,扫描两遍和扫描一遍实现
public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } /** * 扫描两次,第一次确定整个链表的长度 * 第二遍找到倒数第n个 * @param head * @param n * @return */ public static ListNode removeNthFromEnd(ListNode head, int n) { if (head.next == null){ return null; } ListNode res = head; int len = 1; while (head.next!=null){ //倒数第一个在第一遍扫描时候就完成 if (n == 1&& head.next.next ==null){ head.next = null; return res; } head = head.next; len++; } //如果是倒数第一个 if (n == len){ return res.next; } //不是倒数第一个 head = res; int i = 0; while (head.next!=null){ i++; if (len - i == n){ //找到倒数第n个 head.next = head.next.next; return res; } head = head.next; } return res; }
扫描一遍就是设立两个游标,中间间隔为n-1,当后面一个游标走到结束,前一个游标刚好是倒数第n个