链表
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=1e5+5;
class List; //前视定义,否则友元无法定义
class LinkNode
{
friend List; //链表结点类的定义
private:
LinkNode *link;
int data;
public:
LinkNode(const int & item, LinkNode *ptr = NULL)
{
data=item;
link=ptr;
}
LinkNode (LinkNode *ptr = NULL)
{
link=ptr;
}
~LinkNode() { };
};
class List
{
//单链表类的定义
private:
LinkNode *first; //指向首结点的指针
public:
List ()
{
first = new LinkNode ();
}
~List ()
{
MakeEmpty(); //析构函数
}
void MakeEmpty ( ); //链表置空
int Remove (int i); //需要补充的成员函数
void input(int endTag);
void output(); //需要补充的成员函数
};
void List:: MakeEmpty ( )
{
LinkNode *q;
while ( first->link != NULL )
{
q = first->link;
first->link = q->link;
delete q;
}
};
void List :: input (int endTag)
{
LinkNode *newnode,*last;
last=new LinkNode (0);
first->data=0;
int val;
cin>>val;
while(val!=endTag)
{
newnode=new LinkNode (val);
last->link=newnode;
last=newnode;
if(first->data==0)
{
first->data=-1;
first->link=newnode;
}
cin>>val;
}
}
int List :: Remove(int index)
{
cout<<"remove"<<endl;
//cout<<first->link<<endl;
//if(first==NULL)
//return 0;
LinkNode *q=first,*last;
int cnt=0;
while(q->link!=NULL&&cnt<index)
{
last=q;
q=q->link;
cnt=cnt+1;
}
if(q->link==NULL&&cnt!=index)
{
cout<<"Error!!!"<<endl;
return -1;
}
last->link=q->link;
return 0;
}
void List :: output()
{
//cout<<first->link<<endl;
LinkNode *q=first,*last;
//cout<<"答案是"<<endl;
// cout<<first->data<<" ";
while(q->link!=NULL)
{
q = q->link;
cout<<q->data<<" ";
}
cout<<endl;
}
int main()
{
List l;
l.input(0); //0为输入的结束数字
l.output ();
int index;
cin>>index; //要删除的元素的下标,下标从0 开始
l.Remove(index);
l.output (); //删除后输出
l.MakeEmpty();
return 0;
}