线性表的链式表示和实现

线性表的链式表示和实现:

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


#define OK 1
#define ERROR 0
#define OVERFLOW -1


typedef struct LNode {
int data;
struct LNode *next;
}LNode, *LinkList;


int InitList_L(LinkList &L) {
L = (LinkList)malloc(sizeof(LNode));
if(!L) exit(OVERFLOW);
L->next = NULL;
LinkList p = L;

return OK;
}//InitList_L 


int InsertInto_L(LinkList &L, int location, int e) {
LNode *p = L; //指向表头 
int j = 0;


while(p && j<location-1) {
p = p->next;
++j;
}


if(!p || j>location) return ERROR;
LinkList node = (LinkList)malloc(sizeof(LNode));
node->data = e;
node->next = p->next;
p->next = node;


return OK;
}//InsertInto_L


int DeleteList_L(LinkList L, int location) {
LinkList p = L;
int j = 0;

while(p->next && j<location-1) {
p = p->next;
++j;
}
if(!(p->next) || j>location) return ERROR;
LinkList q;
q = p->next;
p->next = p->next->next;
free(q); //释放节点 

return OK;
}//DeleteList_L


int GetElem_L(LinkList L, int location, int &e) {
//L为带头节点的单链表的头指针
//当第i个元素存在时,其赋值给e并返回OK,否则返回ERROR
LNode *p;
p = L->next;
int j =1;
while(p && j<location) {
p = p->next;
++j;
}

if(!p || j>location) return ERROR;
e = p->data;

return e;
}//GetElem_L 


int MergeList_L(LinkList &La, LinkList &Lb, LinkList &Lc) {
LinkList pa,pb,pc;

pa = La->next;
pb = Lb->next;
La = pc = La; //用La的表头作为Lc的表头 

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);
return OK;
}


int main() {
LinkList list;
InitList_L(list);
InsertInto_L(list, 1, 1);
InsertInto_L(list, 2, 3);
InsertInto_L(list, 3, 5);
int e;
e = GetElem_L(list, 2, e);
printf("%d\n", e);
DeleteList_L(list, 2);
e = GetElem_L(list, 2, e);
printf("%d", e);
}


代码要尽量精炼,越打越少,思考多一点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值