前言:
数据结构是一种存储数据的方式,数据结构可以满足你对程序时间和空间的要求,同时数据结构是算法的基础,数据结构就相当于:一个图书馆中的书架,里面存放的每一本书相当于数据。你也可以选择使用乱放这种“数据结构”,只是你寻找的时间会大大加长。学习数据结构,就是为了了解以后在IT行业里搬砖需要用到什么工具,这些工具有什么利弊,应用于什么场景。
一、链表
1、原理
链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的 。如下图所示:
而这里的每一个“块”就是一个结构体。在链表中一个结构体一般包含数据(data)和指针,这个指针是一个结构体指针,每一个结构体指针都指向下一个结构体的地址,让它们能够连接,相比数组他节约了更多的空间,减少了空间的浪费。
2、C语言实现
首先要建立一个“块”,也就是结构体,代码如下:
struct Node{
int data;
struct Node* next;
};
在这个结构体中,我们建立了一个可存放int类型的结构体,在链表里还需要一个头节点,因为链表最后一定是NULL,一开始的链表什么都没有,所以head指向NULL,建立空表。
struct Node* head=NULL;
这时候一个空链表建好了。
3、插入与删除
链表是数据结构的一种,所以他也需要存放数据,这是需要在第n处插入数据数据,代码如下:
struct Node* insert(struct Node* head,int n,int data){
int i;
struct Node* p=(struct Node*)malloc(sizeof(struct Node));
p->next=NULL;
p->data=data;
struct Node* last=head;
if(head==NULL){
head->next=p;
return head;
}
for(i=0;i<n-1;i++){
last=last->next;
}
p->next=last->next;
last->next=p;
return head;
}
当需要删除代码时,删除代码如下 :
struct Node* del(struct Node* head,int n){
int i;
struct Node* last=head;
struct Node* p=NULL;
if(head==NULL){
printf("error");
return head;
}
if(n==1){
head=last->next;
return head;
}
for(i=0;i<n-2;i++){
last=last->next;
}
p=last;
last=last->next;
p->next=last->next;
return head;
}
4、链表的遍历
void print(struct Node* head){
struct Node* last=head;
if(head==NULL){
printf("error");
return;
}
if(last->next==NULL){
printf("%d",last->next);
return;
}
while(last->next!=NULL){
last=last->next;
printf("%d",last->data);
}
printf("%d",last->data);
}
三、知识补充
结构体:C 数组允许定义可存储相同类型数据项的变量,结构是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。