Given a linked list, remove the n-th node from the end of list and return its head.
*Example:
Given linked list : 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:**
Could you do this in one pass?
首先定义一个辅助节点auxList,使它的下一个节点指向链表head,用来简化边界判断的条件,例如一个链表只有一个节点,删除了头节点。第一次遍历(one pass),得到链表的长度L;第二次遍历(two pass)设置一个指针指向辅助节点auxList,并开始删除节点,一直到指定的n停止,此时到达第\(L-n\)个节点;将第\(L-n\)与第\(L-n+2\)个节点重新连接,于是就删除了第\(L-n+1\)个节点(因为人为增加一个节点)。
题目让我们思考,如何通过一次循环来实现对链表倒数N个节点的删除。
链表的搜索
查找链表L中第一个关键字为k的元素,并返回指向该元素的指针。如果链表中没有关键字为k的对象,则返回空(NIL)
//List-Search(L,k)
x = L.head;
while x != NIL and x.key != k //NIL为空
x = x.next
return x
链表的插入
链表的删除
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* auxList = new ListNode(0);
auxList->next = head;
int length = 0;
ListNode* pass = head;
while(pass != NULL){
length ++;
pass = pass->next;
}
length -= n;
pass = auxList;
while(length > 0){
length --;
pass = pass->next;
}
pass->next = pass->next->next;
return auxList->next; //这里返回next是因为auxList的next才是原来的链表
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* auxList = new ListNode(0);
auxList->next = head;
ListNode* point1 = auxList;
ListNode* point2 = auxList;
for(int i = 1; i <= n + 1;i++)
point1 = point1->next;
while(point1 != NULL){
point1 = point1->next;
point2 = point2->next;
}
point2->next = point2->next->next;
return auxList->next;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* auxList = new ListNode(0);
auxList->next = head;
remove(auxList, n);
return auxList->next;
}
int remove(ListNode* head, int n){
if(head->next == NULL)
return 1;
int levels = remove(head->next, n) + 1;
if(levels == n+1)
head->next = head->next->next;
return levels;
}
[1] 算法导论第10章10.2,p131
[2] http://www.cnblogs.com/skywang12345/p/3561803.html
19. Remove Nth Node From End of List[M]删除链表的倒数第N个节点
原文:https://www.cnblogs.com/Jessey-Ge/p/10993506.html