什么是链表?
一种数据结构,链表是按顺序排列的集合。
为什么要使用链表
- 当使用数组时,我们在声明之时,数组的大小就已经固定了。如果我们需要在数组内删除或添加一个数据,需要创建一个新数组来完成。
- 数组分配内存空间是连续分配的,也就是内存空间中必须得存在相应大小的空间,数组才能创建完成。
- 链表在内存空间中是链式存储。可以自适应内存。单向链表中的每个节点存储内容分为两部分:指向下一个节点的地址以及本节点中存储的内容。
链表的基本使用
链表中一般有一个头指针,指向第一个节点。
链表定义
typedef struct linkedList
{
int data;
struct linkedList *next;
}LinkedList;
链表的两种创建方式
头插法
头插法的原理很简单:就是不断更换头指针指针的节点。
LinkedList *insertFromHead(LinkedList *head,LinkedList *new)
{
if(head == NULL){
head = new;
}else{
new->next = head;
head = new;
}
return head;
}
LinkedList *creatLinkedList(LinkedList *head)
{
LinkedList *temp = head;
for(;;){
LinkedList *new = (LinkedList *)malloc(sizeof(LinkedList));
puts("input the data");
scanf("%d",&(new->data));
if(new->data == 0){
free(new);
return head;
}else{
head = insertFromHead(head,new);
}
}
return head;
}
尾插法
尾插法就更简单了
LinkedList *insertBehind(LinkedList *head,LinkedList *new)
{
LinkedList *temp = head;
if(head == NULL){
head = new;
return head;
}
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new;
return head;
}
LinkedList *creatLinkedList2(LinkedList *head)
{
for(;;){
LinkedList *new = (LinkedList *)malloc(sizeof(LinkedList));
puts("input the data");
scanf("%d",&(new->data));
if(new->data == 0){
free(new);
return head;
}else{
head = insertBehind(head,new);
}
}
return head;
}
链表节点的删除
根据节点删除的位置有三种情况。
- 删除首元节点(头指针指向的节点,即第一个节点)。
- 删除中间的节点
- 删除末尾的节点。
LinkedList *deleteNode(LinkedList *head,int location)
{
LinkedList *temp = head;
if(location == 1){
head = temp->next;
free(temp);
return head;
}
int length = getLinekedListLength(head);
if(length == location){
location = location -2;
while(location > 0){
temp = temp->next;
location--;
}
free(temp->next);
temp->next = NULL;
return head;
}
location = location - 2;
while(location > 0){
temp = temp->next;
location--;
}
temp->next = temp->next->next;
free(temp->next);
return head;
}
注意:由于节点是malloc出来的,所以在更改节点指向来删除节点的之前,可以先使用一个临时变量tempNode来存储节点地址,等操作完成后,使用free释放内存。
插入节点
根据节点删除的位置有三种情况。
- 插入首元节点(头指针指向的节点,即第一个节点)。
- 插入中间的节点
- 插入末尾的节点。
LinkedList *insertFromFor(LinkedList *head,int location,LinkedList *newNode)
{
if(head == NULL){
return NULL;
}
LinkedList *temp = head;
if(location == 1){
newNode->next = temp;
head = newNode;
return head;
}
location = location-2;
while(location > 0){
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
return head;
}
查询节点
int searchNode(LinkedList *head,int data){
int location = 0;
int flag = 0;
while(head != NULL){
location++;
if(head->data == data){
flag = 1;
break;
}
head = head->next;
}
if(flag == 0){
return 0;
}
return location;
}