单向链表的建议搭建

来源:互联网 发布:新日铁软件 张涛 编辑:程序博客网 时间:2024/06/14 05:01

前一段时间看了《啊哈算法》这本书,学会了单向链表的搭建。

首先当然是利用struct结构

struct node{
int data;
struct node *next;
};

这里把该结构体看做一部分,即里面有一个存放数据的地方一个存放该类型结构体指针的地方。

然后主要就是利用malloc函数申请内存就可以搭建一个单向的链表了。

int main(void)
{
struct node *head,*p,*q,*t;
int n,a,t;
scanf("%d",&n);
head = NULL;
while(n--)
{
scanf("%d",&a);
p = (struct node*)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(head == NULL)
head = p;
else
q->next = p;//注意这里的q是上一部分的结构体
q = p;//
}
}

如果想再中间插入一个数则只要再申请一块内存把左右两侧结构体指针方向再改变一下即可

完整代码如下。

#include<stdio.h> 
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main(void)
{
struct node *head,*p,*q,*t;
int n,a;
scanf("%d",&n);
head = NULL;
while(n--)
{
scanf("%d",&a);
p = (struct node*)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(head == NULL)
head = p;
else
q->next = p;//注意这里的q是上一部分的结构体
q = p;//
}
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; 
}
t = head;
while(t != NULL)
{
printf("%d ",t->data);
t = t->next;//不断输出下一个链表。 
}
return 0;
}

如果可以请关注下我的公众号




0 0