# include<stdio.h>
# include<stdlib.h>
#include<iostream>
using namespace std;
# define MAXSIZE 50
//静态链表
typedef struct
{
int pos; // 代表在数组中的位置
char data; //代表存放的值
int nextPos; //代表它下一个节点在数组中的位置
}NODE;
//示例输入: 0 a 2 1 f 7 2 b 3 3 c 4 4 d 5 5 e 1 6 h -1 7 g 6
NODE List[MAXSIZE] = { { 0, 'a', 2 },{ 1 ,'f' ,7 } ,{ 2 ,'b', 3 },{ 3, 'c', 4 },{ 4, 'd',5 } ,{ 5, 'e', 1 },{ 6 ,'h', -1 } ,{ 7 ,'g', 6 } };
static int Num = 8;
void Del(int pos)
{
//删除操作只需要将指向它的节点指向下一个即可。例:a->b, b->c, c->d 产出b的话只需要让a指向c即可
for(int i=0;i<Num;i++)
if (List[i].nextPos == pos)
{
List[i].nextPos = List[pos].nextPos;
}
Num--;
}
void Insert(int pos, char ch)
{
List[Num].data = ch;//赋值
List[Num].pos = Num;//先放在最后
for(int i=0;i<Num;i++)
if (List[i].nextPos == pos)
{
List[i].nextPos = Num;//让前一个节点指向它
}
List[Num].nextPos = pos;//再把位置赋值给它的下个节点指针
Num++;
}
void Create()
{
int n;
printf("输入节点个数: ");
scanf("%d", &n);
Num = n;
int temp = 0;
while (temp<n)
{
int p, np;
char ch;
printf("输入第 %d 组数据的位置,值,以及下一个节点的位置: (-1代表空): ", temp + 1);
cin >> List[temp].pos >> List[temp].data >> List[temp].nextPos;
temp++;
}
}
void Print()
{
int i = 0;
while (i != -1)
{
printf("%c\t", List[i].data);
i = List[i].nextPos;
}
cout << endl;
}
int main(void)
{
//Create();
//Del(5);
Insert(2, 'M');
Print();
system("pause");
return 0;
}
静态链表的插入和删除不需要移动元素
静态链表
最新推荐文章于 2022-05-03 20:27:49 发布