- 在分散的内存区域只有地址能唯一标识一个位置,但是在连续的内存中地址和下标都可以唯一的标识一个位置。
- 将连续的内存区划分为多个节点,节点包括存储数据的数据域和指针域
- 用第一个节点记录未使用节点,用最后一个节点记录已使用节点。
#include<iostream> #define LINE 22 typedef int elemtype; class Node { public: elemtype mdata; int cursor; }; class SList { public: SList() { int i = 0; for (i; i < LINE - 2; i++) { node[i].cursor = i + 1; } node[i++].cursor = -1; node[i].cursor = -1; } bool IsEmpty() { if (node[LINE - 1].cursor == -1) { return true; } return false; } void InsterHead(elemtype val)//头插 { if (IsFull()) { return; } int index = node[0].cursor; node[0].cursor = node[index].cursor; node[index].mdata = val; node[index].cursor = node[LINE - 1].cursor; node[LINE - 1].cursor = index; } void InsertTail(elemtype val)//尾插 { if (IsFull()) { return; } int index = node[0].cursor; node[0].cursor = node[index].cursor; node[index].mdata = val; node[index].cursor = -1; int last = LINE - 1; while (node[last].cursor != -1) { last = node[last].cursor; } node[last].cursor = index; } void DeleteKey(elemtype val)//按元素删除某个节点 { if (IsEmpty()) { return; } int index = LINE - 1; int nextindex = node[index].cursor; while (nextindex != -1) { if (node[nextindex].mdata == val) { break; } index = nextindex; nextindex = node[nextindex].cursor; } if (nextindex == -1) { printf("not found!"); return; } node[index].cursor = node[nextindex].cursor; node[nextindex].cursor = node[0].cursor; node[0].cursor = nextindex; } void DeletePos(int pos)//按位置删除某个节点 { if (IsEmpty()) { return; } if (pos == 1 || pos == LINE - 1) { return; } int index = pos; int nextcursor = node[index].cursor; int front = LINE - 1; while (node[front].cursor != -1) { if (node[front].cursor == index) { break; } front = node[front].cursor; } node[front].cursor = node[index].cursor; node[index].cursor = node[0].cursor; node[0].cursor = index; } void Show() { int index = node[LINE - 1].cursor; while (index != -1) { printf("%d ", node[index].mdata); index = node[index].cursor; } printf("\n"); } private: bool IsFull() { if (node[0].cursor == -1) { return true; } return false; } Node node[LINE]; }; int main() { SList sl; int i = 0; for (i; i < 10; i++) { sl.InsterHead(i + 1); } sl.Show(); sl.DeletePos(4); sl.Show(); sl.InsterHead(30); sl.Show(); sl.DeleteKey(30); sl.Show(); return 0; }
静态链表
最新推荐文章于 2024-06-28 13:38:22 发布