题目
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
方案:扫一遍,设置一个length巧妙的使得前后两个节点的保持一定的距离,直到最后一个节点,最后排除删除头部节点的特殊情况即可
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length=0;
ListNode temp_head = head;
ListNode temp_tail = head;
while(temp_tail.next!=null){
temp_tail = temp_tail.next;
if(length<n){
length++;
}else if(length >= n){
temp_head = temp_head.next;
}
}
if (length == n-1){
return temp_head.next;
}else if(length >= n){
temp_head.next = temp_head.next.next;
}
return head;
}
}
复杂度计算