线性表的链式表示(静态链表)
数据结构
typedef struct {
char data;
int next;
}SLinkList[MaxSize];
初始化,求表长
void InitList(SLinkList* S) {
S = (SLinkList*)malloc(sizeof(MaxSize));
S[0]->next = -1;
}
int Length(SLinkList S) {
int ans = 0;
int next = S[0].next;
while (next>=0)
{
next = S[next].next;
ans++;
}
return ans;
}
按序号查找
int GetElem(SLinkList S, int i) {
int next = S[0].next;
while (next >= 0 && i > 1) {
next = S[next].next;
i--;
}
return next;
}
插入元素
void ListInsert(SLinkList& S, int i, char e) {
int p = GetElem(S, i);
int newItem = 1;
while (S[newItem].data>0) {
newItem++;
}
if (newItem == MaxSize - 1) {
printf("超出内存限制,不能继续添加!\n");
return;
}
if (p<0)
{
if (i==1)
{
S[0].next = newItem;
S[newItem].data = e;
return;
}
else {
printf("插入的位置出错!\n");
return;
}
}
int pre;
if (i == 1) {
pre = 0;
}
else {
pre = GetElem(S, i - 1);
}
S[pre].next = newItem;
S[newItem].data = e;
S[newItem].next = p;
}
删除元素
char DeleteList(SLinkList& S, int i) {
int p = GetElem(S, i);
if (p <= 0 || i <= 0) {
printf("删除失败!\n"); return '\0';
}
int next = S[0].next;
int pre;
while (next != i) {
pre = next;
next = S[next].next;
if (next < 0) {
printf("删除失败!\n"); return '\0';
}
}
S[pre].next = S[i].next;
int ans = S[i].data;
S[i].data = NULL;
S[i].next = -1;
return ans;
}
打印数组和链表
void PrintShu(SLinkList S) {
int i = 1;
printf("数组数据:0 ");
while (i<MaxSize)
{
if (S[i].data > 0) {
printf("%c ", S[i].data);
}
else {
printf("0 ");
}
i++;
}
printf("\n");
}
void PrintList(SLinkList S) {
printf("链表数据:");
int next = S[0].next;
printf("(0 0 %d)", next);
while (next > 0) {
printf("(%d %c %d)", next, S[next].data, S[next].next);
next = S[next].next;
}
printf("\n");
}
测试
int main() {
SLinkList S;
InitList(&S);
ListInsert(S, 1, 'a');
PrintList(S);
ListInsert(S, 1, 'b');
PrintList(S);
ListInsert(S, 2, 'c');
PrintList(S);
ListInsert(S, 1, 'd');
PrintList(S);
DeleteList(S, 2);
PrintList(S);
PrintShu(S);
printf("表长:%d\n", Length(S));
return 0;
}
大佬批评指正
|