2018/3/2
数据结构
关于链表的增加和整表遍历练习
若出现errorC4703,更改Vs2017的Sql
#include<stdio.h>
#include<stdlib.h>
/*创建结构体来保存链表*/
struct Node
{
int data;
struct Node *next;//结构体指针
};
int main()
{
struct Node *head, *p, *q, *t;
int i, n, num;
printf("请输入链表的大小\n");
scanf_s("%d", &n);
head = NULL;//初始化头指针
printf("请输入链表的数据");
for (i = 0; i < n; i++)
{
scanf_s("%d", &num);
/*采用尾插法来插入数据*/
/*现将p置于尾指针处*/
p = (struct Node*)malloc(sizeof(struct Node));
p->data = num;
p->next = NULL;//创建尾指针
if (head == NULL)
{
head = p;
}
else
q->next = p;
q = p;
}
/*插入数据*/
printf("请输入待插入的数据");
scanf_s("%d", &num);
/*从头遍历*/
t = head;//指针t只起到了循环遍历的作用
while (t != NULL)//说明没有到尾部
{
if (t->next ==NULL || t->next->data>num)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = num;
p->next = t->next;
t->next = p;
break;
}
t = t->next;
}
/*输出所有数*/
t = head;
while (t != NULL)
{
printf("%2d", t->data);
t = t->next;
}
system("pause");
}