Skip to content

Instantly share code, notes, and snippets.

@wanyakun
Created October 27, 2016 09:31
Show Gist options
  • Save wanyakun/d71037cb4eb543e9e84e08de3b1c68cc to your computer and use it in GitHub Desktop.
Save wanyakun/d71037cb4eb543e9e84e08de3b1c68cc to your computer and use it in GitHub Desktop.
数组、单向链表和双向链表
//
// DoubleLinkTest.c
// DataStructureAndAlgorithm
//
// Created by wanyakun on 2016/10/27.
// Copyright © 2016年 com.ucaiyuan. All rights reserved.
//
#include "DoubleLink.h"
/**
双向链表操作int数据
*/
void intTest() {
int array[4] = {10, 20, 30, 40};
printf("\n----%s----\n", __func__);
createDLink();
insertData(0, &array[0]);
insertData(0, &array[1]);
insertData(0, &array[2]);
printf("DLink is empty = %d\n", isDLinkEmpty());
printf("DLink size = %d\n", dLinkSize());
//打印全部数据
for (int i = 0; i < dLinkSize(); i++) {
char *p = (char *)getNodeData(i);
printf("DLink data at index %d = %s\n", i, p);
}
destroyDLink();
}
void stringTest() {
char *array[4] = {"ten", "twenty", "thirty", "forty"};
printf("\n----%s----\n", __func__);
createDLink();
insertData(0, &array[0]);
insertData(0, &array[1]);
insertData(0, &array[2]);
printf("DLink is empty = %d\n", isDLinkEmpty());
printf("DLink size = %d\n", dLinkSize());
//打印全部数据
for (int i = 0; i < dLinkSize(); i++) {
char *p = (char *)getNodeData(i);
printf("DLink data at index %d = %s\n", i, p);
}
destroyDLink();
}
typedef struct Student {
int id;
char name[20];
} STU;
static STU stuArray[] = {
{10, "Jack"},
{20, "Tom"},
{30, "Willam"},
{40, "Lucy"},
};
#define STU_ARRAY_SIZE (sizeof(stuArray) / sizeof(stuArray[0]))
void objectTest() {
printf("\n----%s----\n", __func__);
createDLink();
insertData(0, &stuArray[0]);
insertData(0, &stuArray[1]);
insertData(0, &stuArray[2]);
printf("DLink is empty = %d\n", isDLinkEmpty());
printf("DLink size = %d\n", dLinkSize());
//打印全部数据
for (int i = 0; i < dLinkSize(); i++) {
STU *p = (STU *)getNodeData(i);
printf("DLink data at index %d = [%d, %s]\n", i, p->id, p->name);
}
destroyDLink();
}
int main(int argc, char const *argv[])
{
intTest();
stringTest();
objectTest();
return 0;
}
1. 数组

数组有上界和下界,数组内的元素在上下界内是连续的。

数组的特点是:数据是连续的;随机访问速度快

数组中稍微复杂一点的是多维数组和动态数组。对于C语言,多维数组本质上也是通过一维数组实现的。动态数组,是指数组的容量能动态增长,对于C语言需要手动实现;对于C++而言, STL提供了Vector;对于Java而言,Collection集合提供了ArrayList和Vector。

2. 单向链表

单向链表(单链表)是链表的一种,它由节点组成,每个节点都包含下一个节点的指针。

单向链表的特点是:节点的链接放心是单向的,相对于数组,单向链表的随机访问速度慢,但是单向链表删除、添加数据的效率很高。

3. 双向链表

双向链表(双链表)是链表的一种。和单链表一样,双链表也是由节点组成,它的每个数据节点中都有两个指针,分别指向直接后继和直接前驱。所以,从双链表中的任意一个节点开始,都可以很方便地访问它的前驱节点和后继节点。一般我们都构造双向循环链表。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment