静态顺序表的基本操作
#include <iostream>
#include <cstdio>
using namespace std;
#define maxsize 50
struct Seqlist
{
int data[maxsize];
int length;
}L;
//静态顺序表初始化:
void initSeqList(Seqlist &L)
{
for (int i = 0; i < maxsize; i ++ ) L.data[i] = 0;
L.length = 0;
}
//在静态顺序表L中,下标为i的位置插入e
bool Seqlist_insert(Seqlist &L, int i/*插在下标为i的地方*/, int e)
{
if(L.length == maxsize || i > L.length || i < 0) return false;
for (int j = L.length - 1; j >= i; j -- )
{
L.data[j + 1] = L.data[j];
}
L.data[i] = e;
++(L.length);
return true;
}
//删除静态顺序表中下标为p的元素,成功返回1,失败返回0
//并将被删除的元素给a带回
bool Seqlist_delete(Seqlist &L, int p, int &a)
{
if(p < 0 || p >= L.length) return false;
a = L.data[p];
for (int i = p; i < L.length - 1; i ++ )
L.data[i] = L.data[i + 1];
--(L.length);
return true;
}
//反转静态顺序表
void reverse(Seqlist &L)
{
int t;
for (int i = 0, j = L.length - 1; i < j; i ++ ,j --)
{
t = L.data[i];
L.data[i] = L.data[j];
L.data[j] = t;
}
return;
}
//按元素值在静态顺序表L中查找e的下标
int find_pos(Seqlist &L, int e)
{
for (int i = 0; i < L.length; i ++ )
if(L.data[i] == e) return i;
return -1;
}
void print(Seqlist &L)
{
for (int i = 0; i < L.length; i ++ ) cout << L.data[i] << ' ';
cout << endl;
return;
}
//按下标查值,并给a带回
bool find_get(Seqlist &L, int p, int &a)
{
if(p < 0 || p >= L.length) return false;
a = L.data[p];
return true;
}
int main()
{
//顺序表初始化
initSeqList(L);
//在顺序表L中,下标为0的位置插入1
Seqlist_insert(L, 0, 1);
Seqlist_insert(L, 1, 3);
Seqlist_insert(L, 1, 2);
//删除静态顺序表中下标为0的元素,成功返回1,失败返回0
//并将被删除的元素给a带回
int a;
if(Seqlist_delete(L, 1, a)) cout << a << endl;
print(L);
//反转顺序表
reverse(L);
reverse(L);
//按元素值在顺序表L中查找4的下标
cout << find_pos(L, 3) << endl;
print(L);
//按元素下标在顺序表L中查值
if(find_get(L, 0, a)) cout << a;
return 0;
}
单链表的基本操作
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int _val) : val(_val), next(NULL) {}
ListNode() {}
};//以下代码都是基于带头节点的单链表
bool initList(ListNode* &L)
{
L = new ListNode(-1);
return true;
}
//头插法建立单链表
ListNode* ListNode_headinsert(ListNode* &L)
{
ListNode* t;
int x;
cin >> x;
while (x != 999)
{
t = new ListNode;
t->val = x;
t->next = L->next;
L->next = t;
cin >> x;
}
return L;
}
//尾插法建立单链表
ListNode* ListNode_tailinsert(ListNode* L )
{
int x;
ListNode* a, *b = L;
cin >> x;
while (x != 999)
{
a = new ListNode;
a->val = x;
b->next = a;
b = a;
cin >> x;
}
b->next = NULL;
return L;
}
void print(ListNode* L)
{
for (ListNode* p = L->next; p != NULL; p = p->next)
cout << p->val << ' ';
cout << endl;
return;
}
bool empty(ListNode* L)
{
if(L->next == NULL) return true;
else return false;
}
int ListNode_length(ListNode* L)
{
int res = 0;
for (ListNode* p = L->next; p; p = p->next) res ++;
return res;
}
int main()
{
ListNode *L;
initList(L);
//ListNode_headinsert(L);
// print(L);
ListNode_tailinsert(L);
print(L);
//注意头节点不算表的长度
cout << ListNode_length(L) << endl;
return 0;
}