单链表的操作(以下均为不带头节点的操作)
单链表中节点类型的描述如下
typedef struct LNode {
int data;
struct LNode* next;
}LNode,*LinkList;
单链表的基本操作
bool InitList(LinkList& L)
bool Empty(LinkList& L)
bool ListInsert1(LinkList& L, int i, int e)
bool ListInsert2(LinkList& L, int i, int e)
bool ListDelete(LinkList& L, int i, int e)
LinkList List_HeadInsert(LinkList& L)
LinkList List_TailInsert(LinkList& L)
int Length(LinkList L)
LNode* LocateElem(LinkList L, int e)
LNode* GetElem(LinkList L, int i)
bool InitList(LinkList& L) {
L = NULL;
return true;
}
bool Empty(LinkList& L) {
if (L == NULL) {
return true;
}
return false;
}
bool ListInsert1(LinkList& L, int i, int e) {
if (i < 1) {
return false;
}
LNode* p = L;
if (p == NULL) {
if (i == 1) {
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = e;
s->next = NULL;
L = s;
}
else {
return false;
}
}
if (i == 1) {
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = e;
s->next = L;
L = s;
return true;
}
int t = 1;
while (p != NULL & t < i-1) {
p = p->next;
t = t + 1;
}
if (p == NULL) {
return false;
}
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool ListInsert2(LinkList& L, int i, int e) {
if (i < 1) {
return false;
}
LNode* s = (LNode*)malloc(sizeof(LNode*));
if (i == 1) {
s->data = e;
s->next = L;
L = s;
return true;
}
int t = 1;
LNode* p = L;
while (p != NULL && t < i - 1) {
p = p->next;
t = t + 1;
}
if (p == NULL) {
return false;
}
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool ListDelete(LinkList& L, int i, int e) {
if (i < 1) {
return false;
}
if (i == 1) {
if (L == NULL) {
return false;
}
else {
LNode* q = L;
L = L->next;
free(q);
}
}
int t = 1;
LNode* p = L;
while (p != NULL && t < i - 1) {
p = p->next;
t = t + 1;
}
if (p == NULL) {
return false;
}
LNode* q = p->next;
p->next = q->next;
free(q);
return true;
}
LinkList List_HeadInsert(LinkList& L) {
int x;
scanf("%d", &x);
while (x != 99) {
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = x;
s->next = L;
L = s;
scanf("%d", &x);
}
return L;
}
LinkList List_TailInsert(LinkList& L) {
int x;
scanf("%d", &x);
LNode* r = L;
if (L == NULL) {
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = x;
s->next = L;
L = s;
r = L;
}
scanf("%d", &x);
while (x != 99) {
LNode* s = (LNode*)malloc(sizeof(LNode*));
s->data = x;
s->next = r->next;
r->next = s;
r = r->next;
scanf("%d", &x);
}
return L;
}
int Length(LinkList L) {
int length = 0;
LNode* p = L;
while (p != NULL) {
length = length + 1;
p = p->next;
}
return length;
}
LNode* LocateElem(LinkList L, int e) {
LNode* p = L;
while (p != NULL) {
if (p->data == e) {
return p;
}
p = p->next;
}
return p;
}
LNode* GetElem(LinkList L, int i) {
LNode* p = L;
int t = 1;
while (p != NULL && t < i) {
p = p->next;
t = t + 1;
}
return p;
}