您的位置:首页 > 理论基础 > 数据结构算法

数据结构 C语言实现 线性表的链式实现

2016-06-20 17:07 267 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/study_sky/article/details/51722050

本节定义的两个类型LNodeType和LinkListType.
LNodeType 为结点,LinkListType为指向LNodeType的指针。
难点在于L_CreatList的参数Lhead为返回数据,类型为指向LNodeType指针的指针(双重指针)。

#include <stdio.h>
#include <stdlib.h>

#include "define.h"

typedef int ElemType;
typedef struct LNode LNodeType;
typedef struct LNode *LinkListType;

struct LNode {
ElemType data;
struct LNode *next;
};

Status L_GetElem(LinkListType Lhead, int i, ElemType *e)
{
LNodeType *p;
int j = 1;
p = Lhead -> next;
while ( p && j < i ){
p = p->next;
++j;
}

if( !p || j > i )
return ERROR;
*e = p->data;
return OK;
}

Status L_ListInsert(LinkListType Lhead, int i, ElemType e)
{
LinkListType p;
int j = 0;
p = Lhead;
while ( p && j < i - 1 ) {
p = p->next;
++j;
}

if ( !p || j > i )
return ERROR;
LinkListType s;
s = (LinkListType ) malloc ( sizeof(LNodeType));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}

Status L_ListDelete(LinkListType L, int i, ElemType *e)
{
LinkListType p, q;
int j;
p = L;
j = 0;
while(p->next && j < i-1 ) {
p = p->next;
++j;
}
if ( !(p->next) || j > i-1)
return ERROR;

q = p -> next;
p->next = q->next;
*e = q->data;
free(q);
return OK;
}

/*
* 逆序创建n个数据的链表
*/
void L_CreateList( LinkListType *Lhead, int n)
{
LinkListType p, L;
int i;
L = (LinkListType)malloc(sizeof(LNodeType));
L->next = NULL;
for ( i = n; i > 0; --i){
p = (LinkListType) malloc(sizeof(LNodeType));
scanf("%d",&p->data);//输入数据的类型限制为整形了。
p->next = L->next;
L->next = p;
}
*Lhead = L;
}

void L_MergeList(LinkListType La, LinkListType Lb, LinkListType *Lc)
{
LinkListType pa,pb,pc;
pa = La->next;
pb = Lb->next;
*Lc = pc = La;
while (pa && pb) {
if (pa->data <= pb->data){
pc->next = pa;
pc = pa;
pa = pa->next;
}else{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
free(Lb);
}

/*
* 以下为随手测试一下
*/

void printList( LinkListType L ){
if (L->next == NULL){
printf("data is empty");
}
L = L->next;
while (L !=NULL){
printf("%d\n", L->data);
L = L->next;
}
}

int main(void)
{
LinkListType L;
L_CreateList(&L, 2);
printf("\n-printList-----\n");
printList(L);
printf("\n--GetElem 1 ----\n");
ElemType e;
L_GetElem(L, 1, &e);
printf("%d\n",e);
L_ListInsert(L, 2, 99);
printf("\n-ListInsert- 2----\n");
printList(L);
printf("\n---ListDelete 1 ---\n");
L_ListDelete(L,1,&e);
printf("e = %d\n", e);
printList(L);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: