#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <initializer_list>
#include <deque>
#include <list>
#include <array>
#include <forward_list>
#include <sstream>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <memory>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <type_traits>
#include <utility>
#include <tuple>
#include <bitset>
#include <regex>
#include <random>
#include <iomanip>
#include <ctime>
#include <cmath>
using namespace::std;
using ElementType = int;
#define ERROR -1
struct LNode;
typedef LNode* PtrToLNode;
typedef PtrToLNode Position;
typedef PtrToLNode List;
struct LNode
{
ElementType Data;
PtrToLNode Next;
};
int Length(List L)
{
Position p;
int cnt = 0;
p = L;
while (p)
{
p = p->Next;
++cnt;
}
return cnt;
}
ElementType FindKth(List L, int k)
{
Position p;
p = L;
int cnt = 1;
while (p&&cnt < k)
{
p = p->Next;
++cnt;
}
if ((cnt == k)&&p)
return p->Data;
else
return ERROR;
}
Position Find(List L,ElementType aim)
{
Position p;
p = L;
while(p)
{
if (aim == p->Data)
return p;
p = p->Next;
}
return nullptr;
}
List Insert(List L, ElementType X, int i)
{
Position tmp, pre;
tmp = (Position)malloc(sizeof(LNode));
tmp->Data = X;
if (i == 1)
{
tmp->Next = L;
return tmp;
}
else
{
int cnt = 1;
pre = L;
while (pre&&cnt < i - 1)
{
pre = pre->Next;
++cnt;
}
if (pre == nullptr || cnt != i - 1)
{
cout << "invalid input i" << endl;
return nullptr;
}
else
{
tmp->Next = pre->Next;
pre->Next = tmp;
return L;
}
}
}
List Insert2(List L, ElementType X, int i)
{
Position pre, tmp;
int cnt = 0;
pre = L;
while (pre&&cnt < i - 1)
{
pre = pre->Next;
++cnt;
}
if (pre == nullptr || cnt != i- 1)
{
cout << "invalid i" << endl;
return nullptr;
}
else
{
tmp = (Position)malloc(sizeof(LNode));
tmp->Data = X;
tmp->Next = pre->Next;
pre->Next = tmp;
return L;
}
}
bool mydelete(List L, int i)
{
Position pre, tmp;
int cnt = 0;
pre = L;
while (pre&&cnt < i - 1)
{
pre = pre->Next;
++cnt;
}
if (pre == nullptr || cnt != i - 1 || pre->Next == nullptr)
{
cout << "invalid delete" << endl;
return false;
}
else
{
tmp = pre->Next;
pre->Next = tmp->Next;
free(tmp);
return true;
}
}
void show(List L)
{
Position p = L->Next;
while (p)
{
cout << p->Data << endl;
p = p->Next;
}
}
int main()
{
PtrToLNode first = (PtrToLNode)malloc(sizeof(LNode));
first->Data = 1;
PtrToLNode second = (PtrToLNode)malloc(sizeof(LNode));
second->Data = 2;
first->Next = second;
second->Next = nullptr;
List L = (List)malloc(sizeof(LNode));
L->Next = first;
Insert2(L, 3, 3);
Insert2(L, 4, 4);
show(L);
mydelete(L, 2);
show(L);
return 0;
}
数据结构第二章线性表代码
最新推荐文章于 2022-11-06 17:49:09 发布