算法描述:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list:1->2->3->4->5
, andn = 2
.
After removing the second node from the end, the linked list becomes1->2->3->5
.
Note:
Given n will always be valid.
Try to do this in one pass.
问题来自此处
解决方案:
这种题的一般思(套)路是:创建两个指针,使两者相隔n个节点,当位于前面的指针指向链表的最后一个结点时,那么位于后面的指针刚好处在链表的倒数第n个结点处。此处我为了删除倒数第n个结点方便,使两个结点相隔n+1个。
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* new_head = head;
ListNode* nth_node = head;
for(int i=1;i<=n;i++){
new_head = new_head->next;
}
if(new_head==NULL) return head->next; //"要删除的结点在原链表中是首个结点"
while(new_head->next){
new_head = new_head->next;
nth_node = nth_node->next;
}
ListNode* del_node = nth_node->next;
nth_node->next = del_node->next;
return head;
}
算法的复杂度,应该是
O(n)
……因为在一次扫描中就完成啦~