C语言实现链表操作
#include "Common.h"
LNode* MakeNode_L(ElemType e) {
LNode* p;
p = (LNode*)malloc(sizeof(struct LNode));
if (NULL == p) return NULL;
p->data = e; p->next = NULL;
return p;
}
Status InitList_L(LinkList& L) {
L = (LNode*)malloc(sizeof(struct LNode));
if (NULL == L) return OVERFLOW;
L->next = NULL;
return OK;
}
Status InsertAfter_L(LNode* p, LNode* q) {
if (NULL == p || NULL == q) return ERROR;
q->next = p->next;
p->next = q;
return OK;
}
Status CreatList_L(LinkList& L, int n, ElemType* A) {
LNode* p, * q;
int i;
if (OVERFLOW == InitList_L(L)) return OVERFLOW;
p = L;
for (i = 0; i < n; i++) {
q = MakeNode_L(A[i]);
InsertAfter_L(p, q);
p = q;
}
return OK;
}
Status CreatList_LH(LinkList& L, int n, ElemType* A) {
LNode* p, * q;
int i;
if (OVERFLOW == InitList_L(L)) return OVERFLOW;
p = L;
for (i = n-1; i >= 0; i--) {
q = MakeNode_L(A[i]);
InsertAfter_L(p, q);
}
return OK;
}
Status CreatList_LN(LinkList& L, int n, ElemType* A) {
int i = 0;
LNode *p = NULL, *q = NULL;
L = NULL;
for (i = n - 1; i >= 0; i--) {
q = MakeNode_L(A[i]);
q->next = L;
L = q;
}
return OK;
}
Status DeleteElem_LH(LinkList& L, int i, ElemType& e) {
LNode *p = L, *q = NULL;
int j = 1;
while ( p->next && j < i)
{
p = p->next;
++j;
}
if (p->next == NULL || j > i) return ERROR;
q = p->next;
e = q->data;
p->next = q->next;
free(q);
return OK;
}
Status DeleteElem_LN(LinkList& L, int i, ElemType& e) {
LNode* p = NULL, * q = NULL;
p = L;
int n = 1;
if (i <= 0) {
return ERROR;
}
if (i != 1) {
while (p != NULL && p->next != NULL) {
if (n == i - 1) {
q = p;
e = p->next->data;
break;
}
n++;
p = p->next;
}
p = q->next;
q->next = p->next;
free(p);
}
else if (i == 1) {
q = L;
L = L->next;
e = q->data;
free(q);
}
return OK;
}
|