您的位置:首页 > 其它

单链表的创建,查找,删除,插入。

2013-11-24 23:25 288 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//定义学生的结构体
typedef struct stu
{
int id;
char name[20];
struct stu * next;
}stu;

//该函数是创建学生信息
stu *Create_chain()
{
stu* head = NULL;
stu* p1 = NULL;
stu* p2 = NULL;
p1 = (stu*)malloc(1*sizeof(stu));
printf("please input a stu infor\n");
scanf("%d%s", &(p1->id), p1->name);
p2 = head = p1;
while(p1->id != 0)
{
p1 = (stu*)malloc(1*sizeof(stu));
printf("please input a stu infor\n");
scanf("%d%s", &(p1->id), p1->name);

p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return head;
}
//该函数是打印学生信息
void Print_chain(stu * head)
{
stu *p;
p = head;
while(p->next != NULL)
{
printf("%-12d%-12s\n",p->id, p->name);
p = p->next;
}

}
//该函数是插入学生信息
void Insert_info(stu* head, stu* temp)
{
stu* p1 = NULL;
stu* p2 = NULL;
p1 = head;
if(head == NULL)
{
head = temp;
temp->next = NULL;
}
else
{
while((p1->next != NULL) && (p1->id<temp->id))
{
p2 = p1;
p1 = p1->next;
}
if(p1->id > temp->id)
{
p2->next = temp;
temp->next = p1;
}
if (p1->next == NULL)
{
p1->next = temp;
temp->next = NULL;
}
}
}

stu* Delete_info(stu* head, int id)
{
stu* p1 = NULL;
stu* p2 = NULL;
p1 = head;

if (head == NULL)
{
printf("not exist stu_info\n");
return head;
}

while((p1->next != NULL)&& (p1->id != id))
{
p2 = p1;
p1 = p1->next;
}
if (p1->id == id)
{
if (p1 == head)
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
}
else
{
printf("not find the stu\n ");
}
return head;
}

void Free_chain(stu* head)
{
stu *p;
p = head;
while(p->next != NULL)
{
free(p);
p = p->next;
}
}

int main()
{
int id ;
stu* head;
stu* tmp = (stu*)malloc(1*sizeof(stu));
head = Create_chain();
Print_chain(head);
puts("please input stu info\n");
scanf("%d%s", &tmp->id, tmp->name);
Insert_info(head, tmp);
Print_chain(head);
printf("please input the id you want delete\n");
scanf("%d\n", &id);
head = Delete_info(head, id);
Print_chain(head);
Free_chain(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐