1.尾插
在单链表的尾部插入新节结点建立单链表的方法称为尾插。
从一个空表开始,重复读入数据,生成新结点,将读入的数据存放到新结点的数据域中,然后将新结点插入当前链表的表尾上。
输入5,6;
输出5,6;
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int n;
struct node *next;
}stu;
int main(){
stu *head;//创建头指针
head=(stu*)malloc(sizeof(stu));
head->next =NULL;//指向空
stu *p;
p=head;
int cnt=2;
while(cnt){
int n;
scanf("%d",&n);
stu *s;//创建新结点
s=(stu*)malloc(sizeof(stu));
s->next=NULL;
s->n =n;
head->next =s;
head=s;
cnt--;
}
head->next =NULL;
stu *i;
for(i=p->next ;i;i=i->next ){//遍历链表
printf("%d",i->n );
}
}
2.头插
、在单链表的头部插入新结点建立单链表的方法简称为头插法;从一个空表开始,重复读入数据,生成新结点,将读入的数据存放到数据域中。、
输入:5 6;
输出:6 5;
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int n;
struct node *next;
}Node;
int main(){
Node *head;//创建头指针
head=(Node*)malloc(sizeof(Node));
head->next=NULL;
int cnt=2;
while(cnt){
int n;
scanf("%d",&n);
Node *s;
s=(Node*)malloc(sizeof(Node));//创建新结点
s->n=n;
s->next =head->next;将新结点指向头节点所指的位置
head->next =s;//进行移位操作
cnt--;
}
Node *i;
for(i=head->next ;i;i=i->next ){
printf("%d\n",i->n );
}
}
3.链表的遍历
在之前我们学过数组的遍历
for(int i=0;i<n;i++){
printf("%d\n",a[i]);
}
我们也可进行链表的遍历
stu *i;
for(i=p->next ;i;i=i->next ){
printf("%d",i->n );
}