链表
数据结构
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Stu_List
{
short ID;
char Name[16];
struct Stu_List* next;
}STU;
STU* new_list(void);
STU* new_list_tail(STU* head);
STU* new_list_head(STU* head);
STU* new_list_insert(STU* head);
STU* new_list_seq(STU* head);
int main(void)
{
int choose;
STU* head = new_list();
if (head == NULL)
return -1;
while (true)
{
printf("请输入你要执行的操作\n 1.增加(尾插法)\t 2.增加(头插法)\t 3.查看\t 4.插入\t 0.退出\n");
scanf("%d",&choose);
switch (choose)
{
case 0:
printf("退出程序\n");
return 0;
case 1:
{
printf("增加新节点(尾插法)\n");
STU* ret = new_list_tail(head);
if (ret == NULL)
return -1;
break;
}
case 2:
{
printf("增加新节点(头插法)\n");
STU* ret = new_list_head(head);
if (ret == NULL)
return -1;
break;
}
case 3:
{
printf("查询\n");
STU* q = head->next;
while (q != NULL)
{
printf("学号:%d \t 姓名: %s \n",q->ID,q->Name);
q = q->next;
}
break;
}
case 4:
{
printf("插入数据\n");
STU* ret = new_list_insert(head);
if (ret == NULL)
return -1;
break;
}
case 5:
{
printf("将现有数据排序\n");
STU* ret = new_list_seq(head);
if (ret == NULL)
return -1;
break;
}
}
}
return 0;
}
STU* new_list(void)
{
STU* head = (STU*)malloc(sizeof(STU));
if (head == NULL)
return NULL;
head->ID = 0;
strcpy(head->Name, "");
head->next = NULL;
return head;
}
STU* new_list_tail(STU* head)
{
STU* node = (STU*)malloc(sizeof(STU));
if (node == NULL)
return NULL;
printf("please enter an ID and Name");
scanf("%d",&(node->ID));
scanf("%s",node->Name);
node->next = NULL;
STU* p = head;
while (p->next != NULL)
p = p->next;
p->next = node;
return node;
}
STU* new_list_head(STU* head)
{
STU* node = (STU*)malloc(sizeof(STU));
if (node == NULL)
return NULL;
printf("please enter an ID and Name");
scanf("%d", &(node->ID));
scanf("%s", node->Name);
node->next = NULL;
node->next = head->next;
head->next = node;
return node;
}
STU* new_list_insert(STU* head)
{
char name[16];
STU* node = (STU*)malloc(sizeof(STU));
if (node == NULL)
return NULL;
printf("请输入你要插入的数据");
scanf("%d",&(node->ID));
scanf("%s",node->Name);
node->next = NULL;
printf("请输入你要插入数据位置的名字");
scanf("%s",&name);
STU* p = head;
while (p->next != NULL)
{
if (strcmp(p->Name, name) == 0)
break;
p = p->next;
}
node->next = p->next;
p->next = node;
return node;
}