单链表增加节点,单链表删除节点

首页 > 经验 > 作者:YD1662022-11-04 00:20:14

单链表中增加节点,除了增加结点本身的数据域和指针域,还需要更改前、后结点的指针域。

一个简单的实例代码:

#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;

}

运行效果如下:

单链表增加节点,单链表删除节点(1)

-End-

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.