ps:用c语言的同学注意一下声明变量要用struct node
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
struct node{
int key;
node *next;
};
node *head,*p,*q,*t;//个人称p为临时指针 q为记录指针
int n;
int main(){
cin>>n;
head=NULL;
int k;
for(int i=1;i<=n;i++){
cin>>k;
p=(node *)malloc(sizeof(node));//为临时结点动态申请空间
p->key=k;
p->next=NULL;
if(head==NULL)head=p;//判断是否为头结点
else q->next=p;
q=p;//q用来记录p(指向
}
cin>>k; //此时希望插入一个数
t=head;
while(t!=NULL){
//如果t走到尾部 或者 t目前所在结点的下一个结点键值是大于当前结点键值的
//则执行插入操作
if(t->next==NULL||t->next->key>k){
p=(node *)malloc(sizeof(node));
p->key=k;
p->next=t->next;
t->next=p;
break;
}
else t=t->next;
}
//输出
t=head;
while(t!=NULL){
cout<<t->key;
t=t->next;
}
return 0;
}
本文介绍了如何使用C语言实现一个动态链表,并演示了如何根据节点值插入保持有序的插入操作。通过`struct node`定义节点结构,展示了内存分配和链表遍历的基本技巧。
3513

被折叠的 条评论
为什么被折叠?



