第一节、线性表

1.顺序表的实现

​ 头文件C.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
#define LISTSIZE 100
typedef int ElemType;
typedef struct
{
ElemType* elem;
int Maxsize;
int length;
}SeqList;
void InitList(SeqList& L);
bool insert(SeqList& L, ElemType x, int i);
void Print(const SeqList L);
void search(SeqList L, ElemType x);
bool del(SeqList& L, int i, ElemType& x);
void free(SeqList& L);

函数文件B.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "C.h"
void InitList(SeqList& L)
{
L.elem = new ElemType[LISTSIZE];
if (L.elem == NULL)
{
printf("内存分配失败!\n");
exit(1);

}
L.length = 0;
L.Maxsize = LISTSIZE;

}
bool insert(SeqList& L, ElemType x, int i)
{
if (i < 0 || i > L.length) return false;
if (L.length == L.Maxsize) return false;
for (int j = L.length - 1; j >= i; j--)
{
L.elem[j + 1] = L.elem[j];
}
L.elem[i] = x;
L.length++;
}
void Print(const SeqList L)
{
for (int i = 0; i < L.length; i++)
{
printf("%d: %d\n",i, L.elem[i]);
}
}
void search(SeqList L,ElemType x)
{
for (int i = 0; i < L.length; i++)
{
if (L.elem[i] == x)
{
printf("%d在顺序表中的位置是%d。\n", x, i + 1);
}
}
}
bool del(SeqList& L, int i, ElemType& x)
{
if (i < 0 || i >= L.length) return false;
x = L.elem[i-1];
for (int j = i; j < L.length - 1; ++j)
{
L.elem[j] = L.elem[j + 1];
}
--L.length;
return true;
}
void free(SeqList& L)
{
if (L.elem)
delete[]L.elem;
L.elem = NULL;
}

main函数

2.单链表的实现

尾插法实现单链表

1.结构体的定义

1
2
3
4
5
 	struct LNode {

int data;
struct LNode* next;
}*LinkNode;

2.尾插法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
LNode * create(int n) {
int i;
struct LNode* head, * p1, * p2=NULL;
int a;
head = NULL;
printf("请输入整数:\n");
for (i = n; i > 0; --i)
{
p1 = (struct LNode*)malloc(sizeof(struct LNode));
scanf("%d", &a);
p1->data = a;
if (head == NULL)
{
head = p1;
p2 = p1;

}
else
{
p2->next = p1;
p2 = p1;

}
}
p2->next = NULL;

return head;
}

void main()
{
int n;
struct LNode* q;
printf("请输入要创建的节点个数:");
scanf("%d", &n);
q = create(n);
printf("结果是:\n");
while (q)
{
printf("%d", q->data);
q = q->next;
}
printf("\n");
}