#include<iostream>
using namespace std;
int a[10]={1,3,2,4,5};
int n=5;
struct node
{
int data;
node *next;
};
void creat_h(node *&head);
void creat_tail(node *&head);
void show(node *&head);
void length(node *&head);
void get(int i,node *&head);
void locate(int x,node *&head);
void insert(int i,int x,node *&head);
void del(int i,node *&head);
void creat_h(node *&head)
{
node *s;
node *p=head;
for(int i=0;i<n;i++)
{
s=new node;
s->data=a[i];
s->next=NULL;
if(i==0)
{
head->next=s;
}
else
{
s->next=head->next;
head->next=s;
}
}
}
void creat_tail(node *&head)
{
node *s;
node *rear=head;
for(int i=0;i<n;i++)
{
s=new node;
s->data=a[i];
s->next=NULL;
rear->next=s;
rear=s;
}
}
void show(node *&head)
{
node *p=head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
void length(node *&head)
{
node *p=head->next;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
cout<<"length:"<<count<<endl;
}
void get(int i,node *&head)
{
node *p=head->next;
int count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p!=NULL)
cout<<"get :"<<p->data<<endl;
}
void locate(int x,node *&head)
{
node *p=head->next;
int count=1;
while(p!=NULL&&p->data!=x)
{
p=p->next;
count++;
}
if(p!=NULL)
{
cout<<"locate:"<<count<<endl;
}
}
void insert(int i,int x,node *&head)
{
node *p=head;
int count=0;
while(p!=NULL&&count<i-1)//查找第i-1个结点,工作指针指向它
{
p=p->next;
count++;
}
node *s=new node;
s->data=x;
s->next=p->next;
p->next=s;
n++;
}
void del(int i,node *&head)
{
node *p=head,*q;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
q=p->next;
p->next=q->next;
delete q;
n--;
}
int main()
{
node *head=new node;
head->next=NULL;
creat_tail(head);
show(head);
length(head);
get(3,head);
locate(5,head);
insert(1,9,head);
insert(6,99,head);
show(head);cout<<endl;
del(5,head);
del(1,head);
show(head);
return 0;
}
推免复习-数据结构-单链表操作
最新推荐文章于 2024-04-04 16:57:53 发布