赞
踩
给你一个链表,删除链表的倒数第 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]
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode[] node = new ListNode[30];
int count = 0;
ListNode temp = head;
while(temp != null){
node[count] = temp;
count++;
temp = temp.next;
}
if(count == n){
return head.next;
}
node[count - n - 1].next = node[count - n].next;
return head;
}
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0,head); dummy.next = head; ListNode slow = dummy; ListNode fast = dummy; while(n-- > 0){ fast = fast.next; } ListNode preNode = slow; while(fast != null){ preNode = slow; slow = slow.next; fast = fast.next; } preNode.next = slow.next; return dummy.next; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。