#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);
}
链表的基本操作
最新推荐文章于 2022-12-26 15:56:22 发布