相关链表的代码

本代码是对链表的建立,及删除,插入,寻找,输出的函数表达

#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
	int date;
	struct node *next;
}node;//建立节点 
node *creatline(node *head,int n)
{
	node *p;
	cout<<"请输入对应链表的数值"<<endl; //输入初始链表的长度 
	for(int i=1;i<=n;i++)
	{
		p=(node*)malloc(sizeof(node));
		int a;
		cin>>a;
		p->date=a;
		p->next=head->next;
		head->next=p;//前插法创建链表 
	}//循环创建链表 
	return head;
}
void printfline(node *head)
{
	node *p;
	p=head->next;//指针p指向第一个数据节点 
	while(p!=head)
	{
		cout<<p->date<<" ";
		p=p->next;//p指针指向下一个节点 
	}//不断输出 
	cout<<endl; 
 } 
 node *san(node *head)//删除函数 
 {int k;
 cout<<"请输入删掉值得位置"<<endl; 
 cin>>k;//k为删掉的位置 
 	node *p,*q,*l;
 	p=head->next;
 	k--;//找到被删节点的前一个节点循环k-1次 
	 while(p!=head)
	 {
	 	while(k--)
	 	{l=p;//循环l指向目标节点前一个节点 
	 		p=p->next;
		 }
		 q=l->next;//用指针q暂存目标点 
		 l->next=l->next->next;//连接节点 
		 free(q);//释放节点 
		 break;
	  } 
	  return head;
 }
 node *cha(node *head)
 {int k,n;
 	node *p,*q,*l;
 	q=(node *)malloc(sizeof(node));//插入需要建立新节点 
 	cout<<"请输入插入的值和要插入的位置"<<endl; 
 	cin>>n>>k;
 	q->date=n;
 	p=head->next;
 	k--;
	 while(p!=head)
	 {
	 	while(k--)
	 	{  l=p;
	 		p=p->next;
		 }//同上找到目标节点的前一个节点 
		 q->next=l->next;
		 l->next=q;//重新连接链表 
		 break;
	  } 
	  return head;
 }
 node *find(node *head)
 {
 	int n;
 	cout<<"请输入要查询值的位置"<<endl; 
 	cin>>n;//输入查询位置 
 	node *p,*l;
 	p=head->next;
 	while(p!=head)
 	{
 		while(n--)
 		{l=p;
 			p=p->next;
		 }
		 break;//找到直接输出 
	 }
	 cout<<l->date;
 }
int main()
{
	node *head,*p,*q;
	head=(node *)malloc(sizeof(node));//头结点创建 
	head->next=head;
	int b;
	cout<<"请输入初始链表的长度"<<endl;
	cin>>b;
	creatline(head,b); //创建初始链表 
	cout<<"输出链表"<<endl; 
	printfline(head);
	cha(head);//插入节点 
	cout<<"输出修改后链表"<<endl; 
	printfline(head);
	san(head);//删除节点 
	cout<<"输出修改后链表"<<endl;
	printfline(head);
	find(head);//查找链表 
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值