静态链表

来源:互联网 发布:旅行者1号 知乎 编辑:程序博客网 时间:2024/05/18 05:38
# 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;}
静态链表的插入和删除不需要移动元素
0 0
原创粉丝点击