单链表中增加节点,除了增加结点本身的数据域和指针域,还需要更改前、后结点的指针域。
一个简单的实例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
char name[15];
int mark;
struct student *next;
}node, *node;
node add(char *value,node head)
{
node p,new;
new = (node)malloc(sizeof(Node));
if(new ==NULL)
{
printf("error");
exit(1);
}
else
{
printf("please input the name:");
scanf("%s",new->name);
printf("please input the mark:");
scanf("%d",&new->mark);
}
p = head->next;
while(p!=NULL)
if(strcmp(p->name,value)==0)
{
new->next = p->next;
p->next = new;
return head;
}
else
p=p->next;
return NULL;
}
void print(node head)
{
node p;
p=head->next;
printf("\nthe record:\n");
while(p!=NULL)
{
printf("name:%s ",p->name);
printf(" mark:%d\n",p->mark);
p=p->next;
}
}
int main()
{
int num,i,j;
char name[15];
node p,pTemp,pTemp2,head;
head = (node)malloc(sizeof(Node));
if(head==NULL)
{
printf("error");
exit(1);
}
else
head->next = NULL;
printf("Please input the number of students:\n");
scanf("%d",&num);
printf("Please input the information:");
for(i=0;i<num;i )
{
p = (node)malloc(sizeof(Node));
if(p==NULL)
{
printf("error");
exit(1);
}
else
{
printf("\nname:");
scanf("%s",p->name);
printf("mark:");
scanf("%d",&p->mark);
if(head->next == NULL)
{
head->next = p;
pTemp=p;
}
else
{
pTemp->next = p;
pTemp=p;
}
}
}
pTemp->next=NULL;
p=head->next;
print(head);
printf("please input the position(student's name) where do you want to insert\n");
scanf("%s",name);
pTemp2 =add(name,head);
if(pTemp2==NULL)
printf("no find");
else
print(head);
system("pause");
return 0;
}
运行效果如下:
-End-