//链表的创建与插入值
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{//定义链表节点
int data;
struct node *next;
};
int main()
{
struct node *head,*q,*p;//需要一个头指针,一个中间变量,一个临时变量
head=NULL;
int ss;
//创建链表
for(int i=0;i<5;i++){
scanf("%d",&ss);
q=(struct node*)malloc(sizeof(struct node));
q->data=ss;
q->next=NULL;
if(head==NULL){
head=q;
}else{
p->next=q;
}
p=q;
}
//打印链表
struct node*t;
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
printf("\n");
//插入值
int temp=6;
t=head;
while(t!=NULL){
if(t==NULL||t->next->data>temp){
struct node*base;
base=(struct node*)malloc(sizeof(struct node));
base->data=temp;
base->next=t->next;//顺序问题一定不能颠倒
t->next=base;
break;
}
t=t->next;
}
//打印链表
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
return 0;
}
链表必须掌握指针,因为模拟链表毕竟有局限性,
malloc函数的返回类型是void*类型,void*表示未确定类型的指针,void*可以转化为任意类型的指针