线性表的链式表示和实现:
#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);
}
代码要尽量精炼,越打越少,思考多一点