C语言链表
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
struct node
{
int data;
struct node *next;
};
struct node * create() //创建链表
{
struct node *head=NULL,*p1,*p2;
p1=p2=(struct node *)malloc(LEN);
scanf("%d",&p1->data);
while (p1->data!=0) {
if (head==NULL) head=p1;
else {
p2->next=p1;
p2=p1;
p1=(struct node *)malloc(LEN);
scanf("%d",&p1->data);
}
}
if (head!=NULL) p2->next=NULL;
return head;
}
void print(struct node *head) //遍历链表
{
struct node *p=head;
while (p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
struct node *insert(struct node *head,int d1,int d2) //插入结点
{
int f=0;
struct node *p=head,*p1,*p2;
while (p!=NULL) {
if (p->data==d1) {
f=1;
p1=(struct node *)malloc(LEN);
p1->data=d2;
p2=p->next;
p1->next=p2;
p->next=p1;
break;}
p=p->next;
}
if (f==0) printf("no\n");
return head;
}
struct node *del( struct node *head ,int d ) //删除结点
{
struct node *p=head;
int f=0;
while(p!=NULL&&p->next!=NULL){
if(head->data==d){
f=1;
head=head->next;
break;
}
else if(p->next->data==d){
f=1;
p->next=p->next->next;
break;
}
p=p->next;
}
if(f==0) printf("no\n");
return head;
}
int main()
{
int d1,d2;
struct node *head;
head=create();
scanf("%d",&d1);
scanf("%d",&d2);
head=insert(head,d1,d2);
print(head);
}

浙公网安备 33010602011771号