【数据结构】顺序表和链表(实现源码)(比较分析)


秃头侠们好呀,今天来聊聊 顺序表和链表

本章重点

1、线性表
2、顺序表
3、链表
4、顺序表和链表的区别和联系
5、缓存命中

线性表

线性表(linear list)是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,
常见的线性表:顺序表、链表、栈、队列、字符串…
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。

在这里插入图片描述

顺序表

概念及结构

顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改

顺序表一般可以分为:

  1. 静态顺序表:使用定长数组存储元素。

在这里插入图片描述
2. 动态顺序表:使用动态开辟的数组存储
在这里插入图片描述

静态顺序表只适用于确定知道需要存多少数据的场景。静态顺序表的定长数组导致N定大了,空间开多了浪费,开少了不够用。所以现实中基本都是使用动态顺序表,根据需要动态的分配空间大小,所以下面我们实现动态顺序表。

接口实现

SeqList.h

#pragma once

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef int SLDataType;


//动态顺序表

typedef struct SeqList
{
	SLDataType* a;
	int size;	//表示数组中有效的元素个数
	int capacity;	//表示实际存储空间容量大小
}SL;

//打印数据
void SeqListPrint(SL* ps);

//初始化
void SeqListInit(SL* ps);

//销毁
void SeqListDestory(SL* ps);

//检查空间是否足够,不够则扩容
void SeqListCheckCapacity(SL* ps);

//尾插
void SeqListPushBack(SL* ps,SLDataType x);

//尾删
void SeqListPopBack(SL* ps);

//头插
void SeqListPushFront(SL* ps, SLDataType x);

//头删
void SeqListPopFront(SL* ps);

//查找元素,找到返回该位置的下标,未找到返回-1
int SeqListFind(SL* ps, SLDataType x);

//指定pos下标位置插入
void SeqListInsert(SL* ps,int pos, SLDataType x);

//指定pos下标位置删除
void SeqListErase(SL* ps, int pos);

SeqList.c

#include"SeqList.h"

//打印数据
void SeqListPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

//初始化
void SeqListInit(SL* ps)
{
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

//销毁
void SeqListDestory(SL* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

//检查空间是否足够,不够则扩容
void SeqListCheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
}

//尾插
void SeqListPushBack(SL* ps, SLDataType x)
{
	SeqListCheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

//尾删
void SeqListPopBack(SL* ps)
{
	//暴力
	assert(ps->size > 0);
	ps->size--;
}

//头插
void SeqListPushFront(SL* ps, SLDataType x)
{
	SeqListCheckCapacity(ps);
	//挪动数据
	int end = ps->size - 1;
	while (end>=0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

//头删
void SeqListPopFront(SL* ps)
{
	assert(ps->size > 0);
	//挪动数据
	int begin = 1;
	while (begin<ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
}

//查找元素,找到返回该位置的下标,未找到返回-1
int SeqListFind(SL* ps, SLDataType x)
{

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

//指定pos下标位置插入
void SeqListInsert(SL* ps, int pos, SLDataType x)
{
	assert(pos>=0&&pos<=ps->size); 
	SeqListCheckCapacity(ps);
	//挪动数据
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
	//有了指定位置插入,就可以将头插尾插替换了
	//分别替换成 
	//SeqListInsert(ps,0,x);	//头插 
	//SeqListInsert(ps,size,x);	//尾插 
}

//指定pos下标位置删除
void SeqListErase(SL* ps, int pos)
{
	assert(pos>=0&&pos<ps->size);
	//挪动数据
	int begin = pos+1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
}
//同样有了指定位置删除,就可以将头删尾删替换了
//分别替换成
// SeqListErase(ps,0);		//头删
// SeqListErase(ps,size-1);	//尾删 

数组相关面试题

1、原地移除数组中所有的元素val,要求时间复杂度为O(N),空间复杂度为O(1)
OJ链接

int removeElement(int* nums, int numsSize, int val)
{
    int dest=0;
    int src=0;
    while(src<numsSize)
    {
        if(nums[src]!=val)
        {
            nums[dest]=nums[src];
            src++;
            dest++;
        }
        else
        {
            src++;
        }
    }
    return dest;
}

2、删除排序数组中的重复项OJ链接

int removeDuplicates(int* nums, int numsSize)
{
    if(numsSize==0)
    {
        return 0;
    }
    int dest=0,src=1;
    while(src<numsSize)
    {
        if(nums[dest]!=nums[src])
        {
            nums[dest+1]=nums[src];
            dest++;
            src++;
        }
        else
        {
            src++;
        }
    }
    return dest+1;
}

3、合并两个有序数组OJ链接

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
    int end1=m-1;
    int end2=n-1;
    int end=m+n-1;
    while(end1>=0&&end2>=0)
    {
        if(nums1[end1]>nums2[end2])
        {
            nums1[end--]=nums1[end1--];
        }
        else
        {
            nums1[end--]=nums2[end2--];
        }
    }
    while(end2>=0)
    {
        nums1[end--]=nums2[end2--];
    }
}

顺序表的缺陷

1、空间不够了需要增容,而增容是需要代价的,realloc分为原地扩和异地扩,当异地扩需要开辟新的空间,拷贝数据,释放旧空间,会有不小的消耗。
2、我们为了避免频繁扩容,增容一般是呈2倍的增长,势必会有一定的空间浪费。例如当前容量为100,满了以后增容到200,我们再继续插入了3个数据,后面没有数据插入了,那么就浪费了97个数据空间。
3、顺序表要求数据从开始位置连续存储,那么我们在头部或者中间插入/删除数据就要挪动数据,时间复杂度最坏为O(N),效率不高,挪动数据就有消耗。

针对以上顺序表的缺陷,就设计出来了链表。

链表

链表的概念及结构

概念:链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的 。

在这里插入图片描述

链表的分类

  1. 单向或者双向
    在这里插入图片描述
  2. 带头或者不带头
    在这里插入图片描述
  3. 循环或者非循环
    在这里插入图片描述
    虽然有这么多的链表的结构,但是我们实际中最常用还是两种结构:
    在这里插入图片描述 1、无头单向非循环链表:结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。另外这种结构在笔试面试中出现很多。
    2、带头双向循环链表:结构最复杂,一般用在单独存储数据。实际中使用的链表数据结构,都是带头双向循环链表。另外这个结构虽然结构复杂,但是使用代码实现以后会发现结构会带来很多优势,实现反而简单了,后面我们代码实现了就知道了。

链表的实现

1、无头+单向+非循环链表增删查改实现

SList.h

#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef int SLTDataType;

typedef struct SListNode
{
	SLTDataType data;
	struct SListNode* next;
}SLTNode;

//开辟空间
SLTNode* BuyListNode(SLTDataType x);

//打印
void SListPrint(SLTNode* phead);

//尾插
void SListPushBack(SLTNode** pphead, SLTDataType x);

//头插
void SListPushFront(SLTNode** pphead, SLTDataType x);

//尾删
void SListPopBack(SLTNode** pphead);

//头删
void SListPopFront(SLTNode** pphead);

//查找
SLTNode* SListFind(SLTNode* phead, SLTDataType x);

//在pos之前插入一个结点
void SListInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x);

//删除pos结点
void SListErase(SLTNode** pphead, SLTNode* pos);

//销毁链表
void SListDestroy(SLTNode** pphead);

SList.c

#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

SLTNode* BuyListNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		printf("malloc fail!\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

void SListPushBack(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = BuyListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		//先找到尾结点处
		SLTNode* tail = *pphead;
		while (tail->next!=NULL)
		{
			tail=tail->next;
		}
		tail->next = newnode;
	}
}

void SListPrint(SLTNode* phead)
{
	SLTNode* cur = phead;
	while (cur != NULL)
	{
		printf("%d-->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SListPushFront(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = BuyListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SListPopBack(SLTNode** pphead)
{
	assert(*pphead!= NULL);

	//剩一个数据
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	//两个及以上个数据
	else
	{
		SLTNode* tail = *pphead;
		while (tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}

void SListPopFront(SLTNode** pphead)
{
	assert(*pphead != NULL);

		SLTNode* next = (*pphead)->next;
		free(*pphead);
		*pphead = next;
}


SLTNode* SListFind(SLTNode* phead, SLTDataType x)
{
	SLTNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}
	return NULL;
}

void SListInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	SLTNode* newnode = BuyListNode(x);
	if (*pphead == pos)
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
	else
	{
		//找到pos前一个结点位置
		SLTNode* posprev = *pphead;
		while (posprev->next!=pos)
		{
			posprev = posprev->next;
		}
		posprev->next = newnode;
		newnode->next = pos;
	}
}

void SListErase(SLTNode** pphead, SLTNode* pos)
{
	if (*pphead == pos)
	{
		SListPopFront(pphead);
	}
	else
	{
		//找到pos前一个结点位置
		SLTNode* posprev = *pphead;
		while (posprev->next != pos)
		{
			posprev = posprev->next;
		}
		posprev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}


void SListDestroy(SLTNode** pphead)
{
	if (*pphead != NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
}

2、带头+双向+循环链表增删查改实现
List.h

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

#include<assert.h>

#include<stdlib.h>

typedef int LTDataType;

typedef struct ListNode 
{
	LTDataType data;
	struct ListNode* next;
	struct ListNode* prev;
}LTNode;

//初始化链表
LTNode* ListInit();

//打印链表
void ListPrint(LTNode* phead);

//创建一个新结点
LTNode* BuyListNode(LTDataType x);

//尾插
void ListPushBack(LTNode* phead, LTDataType x);

//头插
void ListPushFront(LTNode* phead, LTDataType x);

//尾删
void ListPopBack(LTNode* phead);

//头删
void ListPopFront(LTNode* phead);

//查找
LTNode* ListFind(LTNode* phead, LTDataType x);

//在pos指定位置前插入
void ListInsert(LTNode* pos, LTDataType x);

//删除指定位置pos结点
void ListErase(LTNode* pos);

void ListDestroy(LTNode* phead);

List.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"


LTNode* ListInit()
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListPrint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

LTNode* BuyListNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListPushBack(LTNode* phead,LTDataType x)
{
	assert(phead);
	LTNode* tail = phead->prev;
	LTNode* newnode = BuyListNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;

	//有了指定位置插入,就可以省略
	//ListInsert(phead,x);
}


void ListPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = BuyListNode(x);
	LTNode* next = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;


	//有了指定位置插入,就可以省略
	//ListInsert(phead->next,x);
}

void ListPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	tailprev->next = phead;
	phead->prev = tailprev;	
	free(tail);
}

void ListPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* next = phead->next;
	phead->next = next->next;
	next->next->prev = phead;
	free(next);
}

LTNode* ListFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* posprev = pos->prev;
	LTNode* newnode = BuyListNode(x);
	posprev->next = newnode;
	newnode->prev = posprev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(LTNode* pos)
{
	assert(pos);
	LTNode* posprev = pos->prev;
	posprev->next = pos->next;
	pos->next->prev = posprev;
	free(pos);
}

void ListDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}
//记得在test.c中ListDestroy后要把Plist=NULL

顺序表和链表的区别

不同点顺序表链表
存储空间上物理上一定连续逻辑上连续,但物理上不一定连续
随机访问支持,时间复杂度O(1)不支持,时间复杂度O(N)
任意位置插入或者删除元素可能需要搬移元素,效率低,时间复杂度O(N)只需修改指针指向
插入动态顺序表,空间不够时需要扩容没有容量的概念
应用场景元素高效存储+频繁访问任意位置插入和删除频繁
缓存利用率

这两个结构各有优势,没有说谁更优,那就不会出现两个线性表了,严格来说他们两个是相辅相成的。

顺序表
优点:
1、支持随机访问,需要随机访问结构支持的算法可以很好的适用。
缺点:
1、头部,中部插入删除元素时间效率低,O(N)。
2、数组是连续的物理空间,空间不够了我们需要增容。而增容就有一定的消耗,且我们为了避免频繁增容,一般我们一下增容2倍,用不完的可能存在浪费。

链表(双向带头循环链表)
优点:
1、任意位置插入删除,效率高O(1)。
2、按需申请释放空间,没有浪费
缺点:
1、不支持随机访问。(用下标访问),意味着一些排序,二分查找等在这种结构上不适用。
2、链表存储一个值同时要存储链接指针,也有一定的消耗。


还有一点是
顺序表的cpu高速缓存命中率好
而链表的较差

首先我们来看一张图
在这里插入图片描述

缓存命中

假设我们有一个顺序表和一个链表,里面存放了5个int类型的数(如图)
在这里插入图片描述我们知道,程序运行,数据是要被加载到内存中的,内存把数据发送给cpu进行计算,cpu计算好的数据结果再给回内存,内存再把数据给我们,这也就是所谓的冯诺依曼体系结构。我们知道寄存器的内存是很小的,所以当寄存器内存不够用的时候,我们要使用高速缓存(L1 cache , L2 cache , L3 cache)。

现在我们要开始访问数据了,我们遍历顺序表和链表

访问存储数据1的内存位置,先看这个地址在不在缓存中,如果在就直接根据这个地址去访问1,如果不在就是叫未命中,会先把地址加载到缓存之后再访问,但是这里注意的一点是为了提升效率,一般计算机不会只单纯加载1数据的地址,而是往后连续加载比如20个byte的地址数据。对于顺序表,因为顺序表是数组,数组元素的地址是连续的,所以加载一次,就加载了很多数据,而你访问2,3,4,5的时候,就是直接命中了,因为地址已经加载到缓存了。
但是对于链表,我们知道链表的物理地址不是连续的,而我们加载一次,有可能还是没有把后面的数据地址加载进去,后面的还是未命中,还要重新加载。而且造成了缓存污染,因为你加载1数据的时候,我们说了计算机会往后连续一次加载比如20byte的数据地址,但后面的地址都是没用的,反而把缓存中其他的内容挤出去了。对于顺序表那5个元素,如果计算机一次加载20byte,那么一次就全部加载进去了,而链表可能要加载5次,加载100byte才行。


感谢阅读,我们下期再见
如有错 欢迎提出一起交流
关注周周汪

关注三连么么么哒

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周周汪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值