数据结构学习分享
本人大一新生,最近在自学数据结构,写博客监督自己的学习成果.所以我怀着沉重的心情开始写博客。刚开始不怎么会用这个编译器,还请各位前辈大佬多多包含,多多指导。
我们从链表开始分享,首先,是链表的创建。
1.链表的创建
话不多说先上代码。
struct list//链表的结构体
{
int num;
struct list*next;
};
struct list*create(int n)//这里的n用来存储链表的长度;
{
int i;
struct list*p;
struct list*head;
p=head=(struct list*)malloc(sizeof(struct list));//首先创键head节点,p节点。
for(i=0;i<n;i++)//循环用来输入数据
{
struct list*s=(struct list*)malloc(sizeof(struct list));/*一个临时节点s*/
s->num=i;//我们这里为了方便,直接将i的值赋值给节点,在实际的创建中,可以在这里用scanf输入数据
p->next=s;//将p连接上s
p=s;//然后p再到s上
}
p->next=NULL;//链表创建结束,将最后一个节点的next设为NULL
head=head->next;//因为我们的head节点没有值,并不是头,我们要把head指向头,也就是head下一个;
return head;//返回头指针
}
下面给上一段测试代码
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *create(int n)
{
int i;
struct Node* head;
struct Node*p;
p=head=(struct Node *)malloc(sizeof(struct Node));
for(i=0;i<n;i++)
{
struct Node*s=(struct Node *)malloc(sizeof(struct Node));
s->data=i;
p->next=s;
p=s;
}//
p->next=NULL;
head=head->next;
printf("ok");
return head;
}//
int main()
{
int n;
struct Node *head;
printf("输入节点的个数:");
scanf("%d",&n);
head=create(n);
system("pause");
return 0;
}
为了检测create函数是否执行,我们就在create函数体的最后加上了一个printf(“ok”);语句,以判断函数是否成功执行