1、头文件head.h
#ifndef HEAD_H_
#define HEAD_H_
#include<iostream>
struct node
{
node():data(-1),next(static_cast<struct node*>(NULL)){}
node(int x, struct node* p = static_cast<struct node*>(NULL)):data(x),next(p){}
int data;
struct node* next;
};
class LIST
{
public:
LIST();
void push_back(int x);
void push_front(int x);
void Insert(int i, int x);
int Delete(int i);
int GetData(int i);
int Search(int x);
int Size();
void Display();
private:
node* head;
int num;
};
#endif
2、库文件head.cpp
#include"head.h"
using namespace std;
LIST::LIST():num(0),head(new node)
{}
void LIST::push_back(int x)
{
node* it = head;
while(it->next!=NULL)
{
it=it->next;
}
it->next = new node(x);
num++;
}
void LIST::push_front(int x)
{
node *p = new node(x);
p->next = head->next;
head->next = p;
num++;
}
void LIST::Insert(int i, int x)
{
if(i>num)
{
cout<<"插入位置超出界限"<<endl;
return;
}
node* it=head;
for(int j=0; j<i-1; j++)
{
it=it->next;
}
node* p = new node(x);
p->next = it->next;
it->next = p;
num++;
}
int LIST::Delete(int i)
{
if(i>num)
{
cout<<"删除超出范围"<<endl;
return -1;
}
else
{
node *it = head;
for(int j =0;j<i-1;j++)
{
it=it->next;
}
node *p = it->next;
int shuchu = p->data;
it->next = p->next;
delete p;
num--;
return shuchu;
}
}
int LIST::GetData(int i)
{
if(i>num)
{
cout<<"超出范围"<<endl;
return -1;
}
else
{
node* it=head;
for(int j=0;j<i;j++)
{
it=it->next;
}
return it->data;
}
}
int LIST::Search(int x)
{
node* it = head;
int result=0;
while(it->next!=NULL)
{
it=it->next;
if(it->data==x)
{
break;
}
result++;
}
if(result<num)
{
result++;
}
else
{
result=-1;
cout<<"没有元素"<<"x"<<endl;
}
return result;
}
int LIST::Size()
{
int i=0;
node* it=head;
while(it->next!=NULL)
{
it=it->next;
i++;
}
return i;
}
void LIST::Display()
{
node* it=head;
while(it->next!=NULL)
{
it=it->next;
cout<<it->data<<"\t";
}
cout<<endl;
}
3、主程序main1.cpp
#include<iostream>
#include"head.h"
using namespace std;
int main(int argc, char** argv)
{
LIST list;
for(int i=0;i<5;i++)
{
list.push_back(i);
}
list.Display();
list.push_front(22);
list.Display();
list.push_front(33);
list.Display();
list.push_front(44);
list.Display();
list.Delete(3);
list.Display();
list.Insert(3,44);
list.Display();
cout<<list.Size()<<endl;
cout<<"2在第 "<<list.Search(2)<<"个"<<endl;
return 0;
}
|