#include <stdio.h>
#include <stdlib.h>
typedef struct note{
int data;
struct note* next;//指向下一个结点的地址
}note;
int main()
{
note *head,*p,*q,*t,*last;
int n;
scanf("%d",&n);
head=NULL;//头指针初始化为空
for(int i=0;i<n;i++)
{
int a;
scanf("%d",&a);
getchar();
p=(note*) malloc(sizeof(note*));//申请一块note结构体类型的地址存放数据和下一个结点的地址
p->data=a;
p->next=NULL;//下一个结点指向空
if(head==NULL)//若当前是第一个结点
head=p;
else
q->next=p;//上一个结点的next指向这个结点
q=p;
}
last=p;//结尾指向p
t=head;//t指向头指针
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
printf("\n");
while(1) {
int a;
scanf("%d", &a);
if(a==-1)
break;
t = head;
int cot = 0;
if (t->data > a) //若链表中第一个数大于所插入的数,单独处理
{
p = (note *) malloc(sizeof(note *));
p->data = a;
p->next = t;
head = p;//头指针指向新的p
cot = 1;
}
else if (last->data < a) //若链表中最后一个数小于所插入的数,单独处理
{
p = (note *) malloc(sizeof(note *));
p->data = a;
last->next = p;
p->next = NULL;
last = p;//尾指针指向新p
cot = 1;
}
while (t != NULL && cot == 0) {
if (t->next->data > a) {
p = (note *) malloc(sizeof(note *));
p->data = a;
p->next = t->next;
t->next = p;
break;
} else
t = t->next;
}
t = head;
while (t != NULL) {
printf("%d ", t->data);
t = t->next;
}
printf("\n");
}
}
c语言指针链表
最新推荐文章于 2024-10-19 02:13:46 发布