#include<iostream>
using namespace std;
struct node
{
int val;
node *next;
};
node *head,*q; //head是头结点,q指向链表最后一个结点
void Init() //初始化链表,头结点不存值
{
head = new node();
q = head;
}
void Insert(int val) //尾插法
{
node *p = new node();
p->val = val;
q->next = p;
q = p;
q->next=NULL;
}
void Delete(node *t, int x)
{
node *p0 =t, *p1; //p0是前一个,p1后一个
p1=p0->next;
while(p1!=NULL && (p1->val!=x))
{
p0=p1;
p1=p1->next;
}
p0->next = p1->next;
delete p1;
}
int FindByNum(node *t, int num)
{
int i=1;
node *p=t->next;
while(p!=NULL && (i<num))
{
p=p->next;
i++;
}
return p->val;
}
int FindByVal(node *t,int val)
{
node *p=t->next;
while(p!=NULL)
{
if(p->val==val)
{
return 1;
}
p=p->next;
}
return 0;
}
void print()
{
node *p=head->next;
while(p != NULL)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
int n,m;
cin>>n;
Init();
while(n--)
{
cin>>m;
Insert(m);
}
print();
cin>>m;
Delete(head,m);
print();
cin>>m;
cout<<FindByVal(head,m)<<endl;
print();
cin>>m;
cout<<FindByNum(head,m)<<endl;
print();
return 0;
}
链表的基本操作
最新推荐文章于 2022-02-18 19:47:10 发布