总结归纳
代码实现
#define MaxSize 10
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct Node {
int data;
int next;
};
typedef Node SLinkList[MaxSize];
void InitList(SLinkList &L) {
for (int i = 0; i < MaxSize; i++) {
L[i].data = 0;
L[i].next = -2;
}
L[0].next = -1;
}
bool GetValue(SLinkList &L) {
int last = 0;
for (int i = 0; i < 6; i++) {
int address = rand() % 10;
int number = rand() % 80;
if (i == 5) {
L[last].next = -1;
} else {
L[last].next = address;
}
L[last].data = number;
last = address;
}
return true;
}
int GetElem(SLinkList &L, int i) {
if (i < 1) {
return -1;
}
int flag = 0;
int j = 0;
while (L[flag].next != -2 && j < i - 1) {
j++;
flag = L[flag].next;
}
return flag;
}
int GetEmptyNode(SLinkList &L) {
Node p = L[0];
for (int i = 0; i < MaxSize; i++) {
if (L[i].next == -2) {
return i;
}
}
return -1;
}
bool InserstList(SLinkList &L, int i, int e) {
if (i < 1) {
return false;
}
int q = GetEmptyNode(L);
int p = GetElem(L, i - 1);
L[q].data = e;
L[q].next = L[p].next;
L[p].next = q;
return true;
}
bool DeleteList(SLinkList &L, int i, int &e) {
if (i < 1) {
return false;
}
int p = GetElem(L, i);
int q = GetElem(L, i - 1);
cout << L[p].data << " " <<L[p].next << endl;
cout << L[q].data << " " <<L[q].next << endl;
e = L[p].data;
L[q].next = L[p].next;
L[p].data = 0;
L[p].next = -2;
return true;
}
void TraverseList(SLinkList &L) {
for (int i = 0; i < MaxSize; i++) {
if (L[i].next != 0) {
cout << "第" << i << "个:" << L[i].data << " " << L[i].next
<< endl;
}
}
}
int main() {
SLinkList L;
InitList(L);
GetValue(L);
TraverseList(L);
InserstList(L, 3, 5244);
cout << "插入后的效果:" << endl;
TraverseList(L);
int e = -1;
DeleteList(L, 5, e);
cout << "删除的e值:" << e << endl;
TraverseList(L);
}