#include<iostream>
#include <time.h>
#define ERROR 0
#define OK 1
using namespace std;
typedef int ElemType;
typedef int status;
typedef struct Node
{
ElemType data;
struct Node *next;
}Node;
typedef struct Node* LinkList;
status GetElem(LinkList L, int i, ElemType* e)
{
int j;
LinkList p;
p = L->next;
j = 1;
while (p && j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
{
return ERROR;
}
*e = p->data;
return OK;
}
status LinkInsert(LinkList* L, int i, ElemType e)
{
int j;
LinkList p, s;
p = *L;
j = 1;
while (p && j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
{
return ERROR;
}
s = (LinkList)malloc(sizeof(Node));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
status LinkDelete(LinkList* L, int i, ElemType* e)
{
int j;
LinkList p, q;
p = *L;
j = 1;
while (p->next && j < i) //p->next不为空来判断链表中没有数据元素的情况
{
p = p->next;
++j;
}
if (!(p->next) || j > i)
{
return ERROR;
}
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return OK;
}
void CreateListHead(LinkList* L, int n) //在链表头插入元素
{
LinkList p;
int i;
srand(time(0));
*L = (LinkList) malloc(sizeof(Node));
(*L)->next = NULL;
for (i = 0; i < n; i++)
{
p = (LinkList)malloc(sizeof(Node));
p->data = rand() % 100 + 1;
p->next = (*L)->next;
(*L)->next = p;
}
}
void CreateListTail(LinkList* L, int n)//在链表尾插入元素
{
LinkList p, r;
int i;
srand(time(0));
*L = (LinkList)malloc(sizeof(Node));
r = *L;
for (i = 0; i < n; i++)
{
p = (Node*)malloc(sizeof(Node));
p->data = rand() % 100 + 1;
r->next = p;
r = p;
}
r->next = NULL;
}
status ClearList(LinkList* L)
{
LinkList p, q;
p = (*L)->next;
while (p)
{
q = p->next;
free(p);
p = q;
}
(*L)->next = NULL;
return OK;
}
数据结构二线性链表的链式存储结构
最新推荐文章于 2021-11-20 13:36:33 发布