链表的插入 删除 寻找 创建

又教科书可得,权当理解练手
代码分享如下

#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
    
    
   int data;//数据域
   struct _node *next;//指针域
}Node,*pNode;

pNode create(void);//创建动态链表
void output(pNode head);//输出链表元素
void destroy(pNode head);//销毁动态链表,释放内存空间
int find(pNode head,int number);//在链表中查找值为number的元素是否存在
int delnode(pNode head,int number);//删除链表中值为number的结点
int insnode(pNode head,int x,int position);//在指定位置后插入值为x的结点

int main()
{
    
    
	int position,number,flag,x;
	pNode head=NULL;

	head=create();
	output(head);

	printf("输入要查找的数字:");
	scanf("%d",&number);
	position=find(head,number);

	printf("输入要从链表中删除的数字:");
	scanf("%d",&number);
	flag=delnode(head,number);
	output(head);

	printf("输入要插入的元素值和插入元素的位置:");
	scanf("%d%d",&x,&position);
	flag=insnode(head,x,position);
	output(head);

	destroy(head);
	return 0;
}

pNode create(void)
{
    
    
	int number;
	pNode head,p,s;

	head=p=(pNode)malloc(sizeof(Node));//头结点
	head->next=NULL;

	printf("请输入数据(0表示结束输入):\n");
	scanf("%d",&number);
	while(number!=0)
	{
    
    
		s=(pNode)malloc(sizeof(Node));
		s->data=number;
		s->next=p->next;
		p->next=s;
		p=s;
		scanf("%d",&number);
	}
	return head;
}
void output(pNode head)
{
    
    
	pNode p=head->next;
	printf("链表元素为:");
	while(p!=NULL)
	{
    
    
		printf("%d",p->data);
		p=p->next;
	}
	printf("\n");
}
void destroy (pNode head)
{
    
    
	pNode p,q=head;
	while(q!=NULL)
	{
    
    
		p=q;
		q=q->next;
		free(p);
	}
}
int find(pNode head,int number)
{
    
    
	int cnt=1;
	pNode p=head->next;

	while(p->data!=number&&p->next!=NULL)
	{
    
    
		cnt++;
		p=p->next;
	}
	if(p->data!=number)
	{
    
    
		printf("查找的元素%d不在链表中。\n",number);
		return -1;
	}
	printf("查找的元素%d在链表中第%d个位置.\n",number,cnt);
	return cnt;
}
int delnode(pNode head,int number)
{
    
    
	pNode q=head,p=head->next;
	while(p->data!=number&&p->next!=NULL)
	{
    
    
         q=p;
		 p=p->next;
	}
	if(p->data!=number)
	{
    
    
		printf("删除的元素%d不在链表中,删除失败!\n",number);
		return -1;
	}
	else
	{
    
    
		q->next=p->next;
		free(p);
		printf("删除元素%d成功!\n",number);
	}
	return -1;
}
int insnode(pNode head,int x,int position)
{
    
    
	int i=0;
	pNode p=head,s;

	while(i<position&&p->next!=NULL)
	{
    
    
		i++;
		p=p->next;
	}
	if(i<position||position<0)
	{
    
    
		printf("插入的位置不合法!\n");
		return -1;
	}
	s=(pNode)malloc(sizeof(Node));
	s->data=x;
	s->next=p->next;
	p->next=s;
	printf("插入结点成功!\n");
	return 1;
}


分析在代码中,自观

猜你喜欢

转载自blog.csdn.net/yooppa/article/details/115419172
今日推荐