这个题目,可以吧线性单链表的结构的功能循环,循环的功能有查找、获取、删除、长度、遍历。
让我们一起看看题目吧。
样例输入、输出:
这个用不了有参构造函数,那我就可忽略咯。
代码如下:
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
class LinkList{
public:
LinkList(){
first = new Node;
first->next = NULL;
}
void Insert(int i,int x){
Node *s = NULL;
Node *p = first;
int count = 0;
while(p!=NULL&&count<i-1){
p = p->next;
count++;
}
if(p == NULL){
cout<<"位置不正确"<<endl;
return ;
}
else{
s = new Node;
s->data = x;
s->next = p->next;
p->next = s;
}
}
void Search(int x){
Node *p =first;
int count = 0;
while(p != NULL ){
if(p->data == x){
cout<<count<<endl;
return ;
}
count++;
p = p->next;
}
cout<<"None"<<endl;
}
void Get(int i){
Node *p = first;
int count = 0;
while(p != NULL&& count < i){
p = p->next;
count++;
}
if(p == NULL){
cout<<"位置不正确"<<endl;
return ;
}
cout<<p->data<<endl;
}
void Delete(int i){
Node *p = first;
int count = 0;
Node *s = NULL;
if(p == NULL){
cout<<"表空"<<endl;
return ;
}
while(p != NULL&& count < i-1){
p = p->next;
count++;
}
if(p == NULL){
cout<<"位置不正确"<<endl;
return ;
}
s = p->next;
cout<<s->data<<endl;
p->next= s->next;
delete s;
}
void Length(){
Node *p = first->next;
int count = 0;
while(p != NULL){
count++;
p = p->next;
}
cout<<count<<endl;
}
void PrintList(){
Node *p = first->next;
while(p != NULL){
cout<<p->data<<endl;
p = p->next;
}
}
private:
Node *first;
};
int main(){
LinkList list;
char m;
cin>>m;
int n;
int x,y;
while(1){
if(m=='E'){
break;
}
if(m=='I'){
cin>>n;
for(int i = 0;i < n;i ++){
cin>>x;
cin>>y;
list.Insert(x,y);
};
}
if(m=='S'){
cin>>n;
list.Search(n);
}
if(m=='G'){
cin>>n;
list.Get(n);
}
if(m=='D'){
cin>>n;
list.Delete(n);
}
if(m=='L'){
list.Length();
}
if(m=='V'){
list.PrintList();
}
cin>>m;
}
return 0;
}
最后的运行如下,输出的地方都用红框标记咯
这次分享到此就拜拜啦!!!