#include <iostream>
#include <stdio.h>
using namespace std;
class link_list
{
private:
struct node
{
int data;
node *next;
}*head;
public:
link_list()//构造函数
{
head = NULL;
}
~link_list()//析构函数
{
cout<<"析构函数,释放链表!\n";
node *tmp ;
if(head == NULL)
return ;
while(head != NULL)
{
tmp = head->next;
delete head;
head = tmp;
}
}
void insert(int n);//增
void del(int n);//删
bool update(int oldn,int newn);//改
bool seek(int n);//查
void display();
}list;
void link_list::insert(int n)
{
node *tmp,*p;
if(head == NULL)
{
head = new node;//新建头结点
head->data = n;
head->next = NULL;
}
else
{
tmp = head;
while(tmp->next != NULL)
tmp = tmp->next;
p = new node;
p->data = n;
p->next = NULL;
tmp->next = p;
}
}
void link_list::display()
{
node *tmp = head;
if(head == NULL)
{
cout<<"链表为空!\n"<<endl;
return;
}
while(tmp != NULL)
{
cout<<tmp->data<<" ";
tmp = tmp->next;
}
}
void link_list::del(int n)
{
node *tmp = head;
if(tmp->data == n)//删除第一个元素
{
head = tmp->next;
delete tmp;
return ;
}
node *ptr = tmp->next;
while(ptr != NULL)//除了第一个元素外的其他元素
{
if(ptr->data == n)
{
tmp->next = ptr->next;
delete ptr;
return ;
}
ptr = ptr->next;
tmp = tmp->next;
}
cout<<"没有找到该元素!\n"<<endl;
}
bool link_list::update(int oldn,int newn)
{
node *tmp = head;
while(tmp != NULL)
{
if(tmp->data == oldn)
{
tmp->data = newn;
return true;
}
tmp = tmp->next;
}
}
bool link_list::seek(int n)
{
node *tmp = head;
while(tmp != NULL)
{
if(tmp->data == n)
{
return true;
}
tmp = tmp->next;
}
}
int main()
{
link_list list;
//插入操作
cout<<"插入元素:\n";
list.insert(1);
list.insert(3);
list.insert(5);
list.insert(7);
list.insert(9);
list.insert(11);
list.display();
cout<<endl;
//删除操作
cout<<"删除元素:"<<endl;
list.del(1);//删除第一个元素
list.del(7);//删除中间的元素
list.del(11);//删除最后一个元素
list.display();
cout<<endl;
//修改操作
cout<<"修改元素:\n";
if(list.update(3,4))
cout<<"修改成功!\n";
else
cout<<"修改失败,没有找到该元素\n";
list.display();
cout<<endl;
//查找操作
cout<<"查找元素:\n";
if(list.seek(5))
cout<<"找到改元素!\n";
else
cout<<"没有找到该元素!\n";
return 0;
}
c++类的简单实现
最新推荐文章于 2024-04-23 23:03:44 发布