链表的基本操作

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

typedef struct node{
	
	int num;
	struct node * pnext;
}NODE, * PNODE;

PNODE construction(void)
{
	int lenth,val;
	scanf("%d",&lenth);
	
	PNODE pHead = (PNODE)malloc(sizeof(NODE));
	
	if(pHead == NULL)
	{
		printf("wrong !!!\n");
		exit(-1);
	}
	
	PNODE pTlie = pHead;
	pTlie->pnext = NULL;
	
	for(int i = 0; i < lenth; i++)
	{
		PNODE pnew = (PNODE)malloc(sizeof(NODE));
		if(NULL == pnew)
	 	 {
	  	 	printf("内存分配失败,程序退出!\n");
	  		 exit(-1);
	 	 }
		scanf("%d",&val);
		pnew->num = val;
		pTlie->pnext = pnew;
		pnew->pnext = NULL;
		pTlie = pnew;
	}
	
	return pHead;
}

int Find(PNODE pHead,int number)
{
	PNODE p = pHead;
	int i = 0;
	while(p != NULL && p->num != number)
	{
		p = p->pnext;
		i++;
	}
	
	return i;
}

void insert(PNODE pHead,int number,int pos)
{
	PNODE p = pHead;
	int i = 0;
	while(p != NULL && i < pos - 1)
	{
		p = p->pnext;
		i++;
	}
	
	PNODE pnew = (PNODE)malloc(sizeof(NODE));
	if(NULL == pnew)
	 	 {
	  	 	printf("内存分配失败,程序退出!\n");
	  		 exit(-1);
	 	 }
	pnew->num = number;
	pnew->pnext = p->pnext;
	p->pnext = pnew;	
}

void del(PNODE pHead,int pos)
{
	PNODE p = pHead;
	int i= 0;
	while(p != NULL && i <pos - 1)
	{
		p = p->pnext;
		i++;
	}
	
	PNODE q = p->pnext;
	p->pnext = q->pnext;
	free(q); 
	
}

void print(PNODE pHead)
{
	PNODE p = pHead->pnext;
	
	while(p != NULL)
	{
		printf("%d ",p->num);
		p = p->pnext;
	}
	printf("\n");
}


int main(void)
{
	PNODE pHead = NULL;
	pHead = construction();
	print(pHead);
	
	insert(pHead,666,3);
	print(pHead);
	
	del(pHead,4);
	print(pHead);
	
	int o = Find(pHead,666);
	printf("%d",o);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值