一,链表———插入
要往链表中插入6,操作如下。
首先用一个临时指针t从链表的头部开始遍历。
t=head;//从链表头部开始遍历
等到指针t的下一个结点的值比6大的时候,将6插入到中间。即t->next->data大于6时进行插入,代码如下。
scanf("%d",&a);//读入待插入的数
t=head;//从链表头部开始遍历
while(t!=NULL)//当没有到达链表尾部的时候循环
{
if(t->next == NULL||t->next->data > a)
//如果当前结点是最后一个节点或者下一个结点的值大于待插入数的时候插入
{
p=(struct node *)malloc(sizeof(struct node));
p->data = a;
p->next =t->next ;
t->next =p;
break;
}
t=t->next ;
}
完整代码如下。
#include<stdio.h>
#include<string.h>
//创建一个结构体用来表示链表的结点类型
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*