演算法導論 10.2-5 環形鏈表實現字典操作INSERT、DELETE、SEARCH

來源:互聯網
上載者:User
一、題目用環形鏈表來實現字典操作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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.