在指定数据odata前插入ndata数据,如果在链表中找不到此数据,则在结尾插入
struct student
{
int age;
struct student* next;
};
//打印链表
void myprint(struct student* head)
{
struct student* p = head->next;
while (p != NULL)
{
printf("%d ", p->age);
p = p->next;
}
}
//初始化学生链表,在age输入-1时结束
struct student* initStudent()
{
struct student* head;
head = malloc(sizeof(struct student));
head->next = NULL;
struct student* tail;
tail = head;
int val = -1;
while (1)
{
scanf("%d", &val);
if (val == -1)
{
break;
}
struct student* new = malloc(sizeof(struct student));
new->next = NULL;
new->age = val;
tail->next = new;
tail = new;
}
return head;
}
//在指定数据odata前插入ndata数据,如果在链表中找不到此数据,则在结尾插入
void insert(struct student *head,int odata,int ndata)
{
struct student* new = malloc(sizeof(struct student));
new->age = ndata;
new->next = NULL;
struct student* p = head;
while (p->next!=NULL)
{
if (p->next->age==odata)
{
new->next = p->next;
p->next = new;
return;
}
p=p->next;
}
p->next = new;
}
void test()
{
struct student* head= initStudent();
insert(head,20,1000);
insert(head,20,2000);
insert(head,-1,500);
insert(head,30,3000);
myprint(head);
}
int main(void)
{
test();
system("pause");
return EXIT_SUCCESS;
}