给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:遍历两边,第一遍取length,第二遍删除n节点
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0;
ListNode cur = head;
while(cur != null){
length++;
cur = cur.next;
}
cur = head;
int index = length - n;//正数第index个
//删除头结点
if(index == 0)
return head.next;
for(int i=1;i<index;i++)
cur = cur.next;
cur.next = cur.next.next;
return head;
}
思路2:遍历一遍,利用快慢指针
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode root = new ListNode(0);
ListNode fast=root,slow=root;
root.next = head;
for(int i=0;i<=n;i++)
fast=fast.next;
while(fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return root.next;
}