#include<stdio.h>
struct SQList/*定义顺序表每个元素的结构*/
{
int data;
struct SQList * next;
};
struct SQList * SQInsert(struct SQList * list)/*插入一个元素*/
{
struct SQList * temp = list;/*临时保存原先的list*/
list = (struct SQList *)malloc(sizeof(struct SQList));/*新建一个元素*/
printf("data:");/*提示输入*/
scanf("%d", &(list->data) );/*将输入数值放到新元素中*/
list->next = temp;/*将新元素和原先的顺序表串接起来, 成为一个新的顺序表*/
printf("\n");
return list;/*返回新顺序表*/
}
void SQPrint(struct SQList * list)
{
struct SQList * temp = list;/*用temp打印输出, 以免破坏顺序表*/
while(temp != NULL)/*元素不为空则一直打印*/
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void main()
{
struct SQList * list = NULL;
char select;
while(1)
{
printf("I:Insert, P: Print.\n");
printf("please select:");
select = getchar();/*select记录用户的选择, 在下面的switch时做判断使用*/
/*需要添加功能的话也很容易, 只要在下面的switch中添加一个case就可以, 比如加入一个删除功能, 可以case 'D': SQDelete(list), 然后在main前面编辑这个SQDelete函数就可以啦, 再在前面的输入提示那里显示D: delete就更完善啦*/
switch(select)
{
case 'I':
list = SQInsert(list);
break;
case 'P':
SQPrint(list);
break;
default:
printf("invalid input.\n\n");
break;
}
getchar();/*清除输入的回车*/
}
}
温馨提示:答案为网友推荐,仅供参考