您的位置:首页 > 职场人生

[剑指offer][面试题13]在O(1)时间删除链表结点

2013-10-12 11:53 573 查看
给定链表的头指针和一个结点指针,在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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: