[剑指offer][面试题13]在O(1)时间删除链表结点
2013-10-12 11:53
627 查看
给定链表的头指针和一个结点指针,在O(1)时间内删除该结点。
#include <iostream> using namespace std; struct Node{ int m_Data; Node *m_pNext; }; /* Assumption the node to be deleted is in the list. * Given the head and the node pointers, try to delete the node in O(1) time. */ void deleteNodeFromList(Node **ppHead, Node *pNodeToBeDeleted) { if (ppHead==NULL || *ppHead==NULL || pNodeToBeDeleted==NULL){ return; } Node *pHead = *ppHead; //case1: the list contains only one node. if (pNodeToBeDeleted==pHead && pHead->m_pNext==NULL){ delete pHead; *ppHead = NULL; return; } //case2. the list contains at least two nodes, and the node to be deleted is the last node. if (pNodeToBeDeleted->m_pNext==NULL){ while (pHead->m_pNext!=pNodeToBeDeleted){ pHead = pHead->m_pNext; } pHead->m_pNext = NULL; delete pNodeToBeDeleted; pNodeToBeDeleted = NULL; return; } //case3. the list contains at least two nodes, and the node to be deleted is not the last node. Node *pNext = pNodeToBeDeleted->m_pNext; pNodeToBeDeleted->m_Data = pNext->m_Data; pNodeToBeDeleted->m_pNext = pNext->m_pNext; delete pNext; pNext = NULL; } void printList(Node *pHead) { bool bEmpty = true; while (pHead){ bEmpty = false; cout<<pHead->m_Data<<"->"; pHead = pHead->m_pNext; } if (!bEmpty){ cout<<"NULL"<<endl; } } int main() { Node *pNode0 = new Node; pNode0->m_Data = 0; Node *pNode1 = new Node; pNode1->m_Data = 1; Node *pNode2 = new Node; pNode2->m_Data = 2; Node *pNode3 = new Node; pNode3->m_Data = 3; Node *pNode4 = new Node; pNode4->m_Data = 4; pNode0->m_pNext = pNode1; pNode1->m_pNext = pNode2; pNode2->m_pNext = pNode3; pNode3->m_pNext = pNode4; pNode4->m_pNext = NULL; Node **ppHead = &pNode0; printList(*ppHead); cout<<"\n delete node: "<<pNode0->m_Data<<endl; deleteNodeFromList(ppHead, pNode0); printList(*ppHead); cout<<"\n delete node: "<<pNode4->m_Data<<endl; deleteNodeFromList(ppHead, pNode4); printList(*ppHead); cout<<"\n delete node: "<<pNode2->m_Data<<endl; deleteNodeFromList(ppHead, pNode2); printList(*ppHead); }
相关文章推荐
- 剑指Offer----面试题13:在O(1)时间删除链表结点
- 【面试题】剑指offer13--在O(1)时间删除链表结点
- 剑指offer-面试题 13:在 O( 1)时间删除链表结点
- 剑指Offer面试题12打印1到最大的n位数,面试题13在O(1)时间删除链表结点
- 剑指offer--面试题13:在O(1)时间删除链表结点--Java实现
- 剑指offer-面试题13-在O(1)时间删除链表结点
- 剑指offer之面试题13在O(1)时间删除链表结点
- 【剑指Offer】面试题13:在O(1)时间删除链表结点
- 【剑指offer 面试题13】在 O(1) 时间删除链表结点
- 【剑指Offer学习】【面试题13 :在O(1)时间删除链表结点】
- 剑指offer--面试题13:在O(1)时间删除链表结点
- 剑指Offer_面试题13_在O(1)时间删除链表结点
- 剑指offer--面试题13:在O(1)时间删除链表结点--Java实现
- 【剑指offer】面试题13:在O(1)时间删除出链表结点
- 剑指offer面试题13——在O(1)时间删除链表结点
- 【剑指offer】面试题13、在 O(1)时间上删除链表结点
- 剑指offer面试题13-在O(1)时间删除链表的节点
- 剑指offer13 在O(1)时间删除链表的结点
- 剑指offer--面试题13:在O(1)时间删除链表节点
- 剑指Offer-13-在O(1)时间删除链表结点