在O(1)时间内删除链表结点
题目:给定链表的头指针和一个结点指针,在O(1)时间内删除该结点,链表结点的定义如下:
struct ListNode { int m_nKey; ListNode* m_pNext; };
函数的声明如下:
void DeleteNode(ListNode *pListHead, ListNode *pToBeDeleted);
答:
#include "stdafx.h" #include <iostream> #include <fstream> #include <ctime> using namespace std; struct ListNode { int m_nKey; ListNode* m_pNext; }; //构造链表 void CreateList(ListNode *&pHead, fstream &fin, ListNode *&pToBeDeleted) { ListNode *pNode = NULL; ListNode *pTmp = NULL; int data; fin>>data; srand((unsigned)time(NULL)); while (data) { pNode = new ListNode; pNode->m_nKey = data; pNode->m_pNext = NULL; if (NULL == pHead) { pHead = pNode; pTmp = pNode; } else { pTmp->m_pNext = pNode; pTmp = pNode; } if (NULL == pToBeDeleted && !(rand() % 5)) { pToBeDeleted = pNode; } fin>>data; } } //在O(1)时间内删除链表结点 void DeleteNode(ListNode *pListHead, ListNode *pToBeDeleted) { if (NULL != pToBeDeleted->m_pNext) { ListNode *pRealDeleted = pToBeDeleted->m_pNext; pToBeDeleted->m_nKey = pRealDeleted->m_nKey; pToBeDeleted->m_pNext = pRealDeleted->m_pNext; delete pRealDeleted; } else { ListNode *pNode = pListHead; while (NULL != pNode) { if (pNode->m_pNext == pToBeDeleted) { pNode->m_pNext = NULL; delete pToBeDeleted; break; } pNode = pNode->m_pNext; } } } //输出链表 void PrintList(ListNode *pHead) { if (NULL == pHead) { return; } ListNode *pNode = pHead; while (NULL != pNode) { cout<<pNode->m_nKey<<" "; pNode = pNode->m_pNext; } cout<<endl; } int _tmain(int argc, _TCHAR* argv[]) { fstream fin("list.txt"); ListNode *pHead = NULL; ListNode *pToBeDeleted = NULL; CreateList(pHead, fin, pToBeDeleted); cout<<"原来的链表:"; PrintList(pHead); DeleteNode(pHead, pToBeDeleted); cout<<"删除后链表:"; PrintList(pHead); cout<<endl; return 0; }
运行界面如下:
建造链表的list.txt文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0