単一チェーンテーブルの挿入削除操作(c++実装)
次のコードは、単一チェーンテーブルのシーケンス挿入、チェーンテーブル要素の削除、チェーンテーブルの出力を実現します.
しゅプログラム
// mylink.h
#ifndef MYLINK_H
#define MYLINK_H
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class list
{
public:
list()
{
head=NULL;
};
void insert(int item);
void del(int item);
void show();
private:
node *head;
};
void list::insert(int item) //
{
node *p=new node();
p->data=item;
p->next=NULL;
if(head==NULL) //
{
head=p;
}
else
{
node *q,*r;
q=head;
while(q&&q->data<=p->data)
{
r=q;
q=q->next;
}
if(q!=NULL)
{
p->next=q;
r->next=p;
}
else
{
p->next=NULL;
r->next=p;
}
}
}
void list::del(int item)
{
if(head==NULL)
{
cout<<" , "<<endl;
}
else if(head->data==item)
{
head=head->next;
}
else
{
int flag=1;
while(flag) // item
{
node *p=head;
node *q;
while(p&&p->data!=item)
{
q=p;
p=p->next;
}
if(p) //
q->next=p->next;
else
flag=0;
}
}
}
void list::show()
{
node *p;
p=head;
if(head==NULL)
{
cout<<" "<<endl;
}
else
{
cout<<" :";
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
}
#endif
しゅプログラム
// main.cpp
#include "mylink.h"
#include<iostream>
using namespace std;
int main()
{
list L;
L.insert(1);
L.insert(3);
L.insert(2);
L.insert(5);
L.insert(2);
L.insert(3);
L.show();
L.del(2);
cout<<" 2 :"<<endl;
L.show();
L.del(3);
cout<<" 3 :"<<endl;
L.show();
cout<<"OK"<<endl;
system("pause");
return 0;
}