题目
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
分析:
设length为链表的长度,删除倒数第n个元素,其实也就是删除正数的第length-n+1个,也就是指针从左向右遍历,走到第length-n这个位置,然后改变这个位置的节点的next指针,指向其下一个节点的next指向的位置即可。
实现代码:
public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null){ return null; } int length = 0; ListNode p = head; while (p != null){ length++; p = p.next; } p = head; if (length == n){ head = head.next; return head; } int steps = length - n; while (--steps > 0){ p = p.next; } p.next = p.next.next; return head; }