一、題目用環形鏈表來實現字典操作INSERT、DELETE、SEARCH,並給出它們的已耗用時間二、代碼
//List.h#include <string>using namespace std;//鏈表結點struct node{node *next;int key;node(int x):next(NULL),key(x){}};//鏈表struct list{node *Head;//頭結點,作為哨兵list():Head(){Head = new node(0);Head->next = Head;};};//插入void Insert(list *L, int x){//構造一個新的結點node *A = new node(x);//找到應當插入的位置node *p = L->Head->next, *q = L->Head;while(p != L->Head && p->key < x){q = p;p = p->next;}//插入結點q->next = A;A->next = p;}//刪除int Delete(list *L, node *A){//找到結點的前一個結點,因為是單鏈表,要迴圈整個鏈表直到找到這個結點的前一個結點node *p = L->Head->next, *q = L->Head;while(p != L->Head && p != A){q = p;p = p->next;}//沒找到if(p == L->Head){cout<<"error:not found"<<endl;return -1;}//找到了,修改指標int ret = p->key;q->next = A->next;delete A;return ret;}//尋找值為x的指標node* Search(list *L, int x){//遍曆整個鏈表尋找這個結點node *p = L->Head->next;while(p != L->Head && p->key < x)p = p->next;//沒找到,返回NULLif(p == L->Head || p->key > x){cout<<"error:not found"<<endl;return NULL;}//找到了,返回結點return p;}//列印void Print(list *L){node *p = L->Head->next;while(p != L->Head){cout<<p->key<<' ';p = p->next;}cout<<endl;}三、測試
#include <iostream>#include <string>#include "List.h"using namespace std;//測試int main(){list *L = new list;int x;string str;while(1){cin>>str;if(str == "I"){cin>>x;Insert(L, x);}else if(str == "D"){cin>>x;node *A = Search(L, x);if(A)Delete(L, A);}else if(str == "P")Print(L);}return 0;}