一、前言
接上一篇顺序表,本篇文章采用链式结构实现运算。
二、链接表示
这种存储结构不要求逻辑关系上相邻两个元素在物理位置上也相邻存储,而是通过增加指针来指示元素之间的逻辑关系和后继元素的位置。
三、结点类型和单链表类型
struct node
{
int data;//存放整型数据的 data 成员
struct node *next;//指向下一个结点的next成员
};
四、c语言实现
完成创建一个带表头的空链表的操作
创建一个只有一个头结点的空链表,头节点的数据域赋值为0,并将表头结点的地址返回
struct node *mycreateList()
{
struct node *head = (struct node*)malloc(sizeof(struct node));
head->data = 0;
head->next = NULL;
return head;
}
1.编写一个能向表头插入结点的函数;
实现在head为表头d 链表的头插数据元素insData的功能
void myinsertHead(struct node *head,int insData)
{
struct node *d = (struct node*)malloc(sizeof(struct node));
d->data = insData;
d->next = head->next;
head->next = d;
}
2.编写一个能在表尾插入结点的函数;
在head为表头的单链表表尾插入数据元素insData
void myinsertTail(struct node*head,int insData)
{
struct node *pRear = head;
while(pRear->next!=NULL)//找到“尾巴”
{
pRear = pRear->next;
}
struct node *d = (struct node*)malloc(sizeof(struct node));
d->data = insData;
d->next = NULL;
pRear->next = d;//新结点插入链表中
pRear = d;//更新尾部指针指向
}
3.编写一个能遍历链表并输出链表各结点数据元素的函数;
输出head为表头链表中的数据,每输出一个数据换一行
void myprintList(struct node *L)
{
if(L == NULL)return;
struct node *pCurrent = L->next;
while(pCurrent != NULL)
{
printf("%d\n",pCurrent->data);
pCurrent = pCurrent->next;
}
}
链表逆置
后续会整理单独一篇链表逆置功能的实现~
void reverseList_link(struct node *L)
{
struct node *p = L->next;
struct node *q = p->next;
struct node *r = q->next;
p->next = NULL;
while(r)
{
q->next = p;
L->next = q;
p = q;
q = r;
r = r->next;
}
q->next = p;
L->next = q;
}
查找和交换
在头结点为L的链表中查找与data值相等的第一个结点,若能找到该结点,则将该结点的值与前驱结点的值交换
若未找到与data值相等的结点,则返回值为-1,若找到的结点无前驱结点,则返回值为0,否则返回值为前驱结点的值
int locateAndChange(struct node *L, int data)
{
int index = 1;//记录位置:方便找到交换的值
int temp;
struct node *p = L->next;
struct node *q = L->next;
struct node *r;
while(p != NULL)
{
if(p->data == data)
{
if(index == 1)return 0;//找到的结点没有前驱
for(int t = 1;t<index-1;t++)q = q->next;//找前驱结点
temp = q->data;
q->data = p->data;
p->data = temp;
return temp;
}
index++;
p = p->next;
}
return -1;
}
链表销毁
实现将链表L的结点空间回收
返回值为回收结点的个数,含头结点在内
int destroyList(struct node *L)
{
int num = 0;
struct node *p = L;
while(p)
{
L = L->next;
free(p);
num++;
p = L;
}
return num;
}