#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define OVERFLOW -1
#define ERROR 0
typedef int Status;
typedef int ElemType;
//单链表(LinkList)
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode, * LinkList;
Status GetElem_L(LinkList L, int i, ElemType* e)
{
LNode* p = L->next;
int j = 1;
while (p && j < i)
{
p = p->next;
j++;
}
if (!p) return ERROR;
*e = p->data;
return OK;
}
Status ListInsert_L(LinkList L, int i, ElemType e)
{
LNode* p = L->next, * q;
for (int j = 1; p && j < i - 1; j++)
p = p->next;
if (!p) return ERROR;
q = (LinkList)malloc(sizeof(LNode));
if (!q) exit(OVERFLOW);
q->data = e;
q->next = p->next;
p->next = q;
return OK;
}
Status ListDelete(LinkList L, int i, ElemType* e)
{
LNode* p = L->next, * q;
for (int j = 1; p && j < i - 1; j++)
p = p->next;
if (!p || !p->next) return ERROR;
q = p->next->next;
free(p->next);
p->next = q;
return OK;
}
void CreatList_L(LinkList L, int n)
{
L = (LinkList)malloc(sizeof(LNode));
if (!L) exit(OVERFLOW);
L->next = NULL;
int i = n, e;
LNode* p;
while (i > 0)
{
printf("请输入第%d个值\n", n - i + 1);
scanf("%d", &e);
p = (LinkList)malloc(sizeof(LNode));
if (!p)exit(OVERFLOW);
p->data = e;
p->next = L->next;
L->next = p;
i--;
}
}
Status MergeList_L(LinkList La, LinkList Lb, LinkList Lc)
{
LNode* pa = La->next, * pb = Lb->next, * pc, * tail = Lc;
tail = (LinkList)malloc(sizeof(LNode));
if (!tail) exit(OVERFLOW);
while (pa && pb)
{
pc = (LinkList)malloc(sizeof(LNode));
if (!pc) exit(OVERFLOW);
if (pa->data < pb->data)
{
pc->data = pa->data;
pa = pa->next;
}
else
{
pc->data = pb->data;
pb = pb->next;
}
pc = tail->next;
tail = pc;
}
while (pa)
{
pc = (LinkList)malloc(sizeof(LNode));
if (!pc) exit(OVERFLOW);
pc->data = pa->data;
pa = pa->next;
}
while (pb)
{
pc = (LinkList)malloc(sizeof(LNode));
if (!pc) exit(OVERFLOW);
pc->data = pb->data;
pb = pb->next;
}
return OK;
}
//双链表(Double Link List)
typedef struct DuLNode
{
ElemType data;
struct DuLNode* prior, * next;
}DuLNode, * DuLinkList;
Status ListInsert_DuL(DuLinkList L, int i, ElemType e)
{
DuLNode* p = L->next, * q;
int j;
for (j = 1; j < i && p; j++)
p = p->next;
if (!p && j < i - 1) return ERROR;
q = (DuLNode*)malloc(sizeof(DuLNode));
if (!q) exit(OVERFLOW);
q->data = e;
if (!p && j == i - 1)
{
p = L->next;
while (p->next)
p = p->next;
p->next = q;
q->prior = p;
q->next = NULL;
}
else
{
q->next = p;
q->prior = p->prior;
p->prior = q;
p->prior->prior->next = q;
}
return OK;
}
Status ListDelete_DuL(DuLinkList L, int i, ElemType* e)
{
DuLinkList p = L->next;
for (int j = 1; p && j < i; j++)
p = p->next;
if (!p) return ERROR;
p->prior->next = p->next;
p->next->prior = p->prior;
*e = p->data;
free(p);
return OK;
}
严蔚敏数据结构线性表的链式存储结构
于 2022-05-06 15:48:39 首次发布
本文介绍C/C++中单链表和双链表的定义与操作,包括获取元素、插入、删除,以及如何使用MergeList_L函数合并两个单链表。重点展示了ListInsert_L、ListDelete和MergeList_L的详细实现及其应用场景。
摘要由CSDN通过智能技术生成