推免复习-数据结构-单链表操作

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值