#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *init()
{
node *head;
head=(node*)malloc(sizeof(node));
head->next=NULL;
return head;
}
void display(node *head)
{
node *p;
p=head->next;
if(!p)
printf("该头节点所指向的单链表为空");
else
{
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
}
node *find(node *head,int i)
{
node *p=head;
int j=0;
if(i<0)
{
printf("该链表中不存在第%d个节点\n",i);
return NULL;
}
else if(i==0)
return p;
while(p&&i!=j)
{
p=p->next;
j++;
}
return p;
}
node *insert(node *head,int data,int i)
{
node *p,*q;
q=find(head,i);
if(q==NULL)
{
printf("不能插入第%d个数据:%d\n",i,data);
return head;
}
p=(node*)malloc(sizeof(node));
p->data=data;
p->next=head->next;
head->next=p;
}
node *dele(node *head,int data)
{
node *p,*pre;
pre=head;
p=head->next;
while(p&&p->data!=data)
{
pre=p;
p=p->next;
}
if(pre)
{
pre->next=p->next;
//printf("%d\n",p->data);
free(p);
//printf("yes %d\n",p->data);
}
return head;
}
int main()
{
node *head=init();
int i;
for(i=0; i<10; i++)
insert(head,i,i);
node *d=find(head,3);
printf("%d %d\n",3,d->data);
dele(head,3);
display(head);
printf("%d %d\n",3,d->data);
return 0;
}
指针复习之单链表实现
最新推荐文章于 2024-03-10 22:37:26 发布