1 代码
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef char ElemType;
typedef struct LNode{
ElemType data;
LNode *next;
}LNode, * LinkList;
bool InitList(LinkList &L);
bool Empty(LinkList& L);
bool Empty(LinkList& L) {
if (L->next == NULL) {
return false;
}
return true;
}
void PrintElement(LinkList L) {
LNode* p = L->next;
int i = 1;
while(p != NULL) {
cout << "[index: " << i << ", Element: " << p->data << " ]" << endl;
p = p->next;
i++;
}
}
int GetLinkListLen(LinkList L) {
int nodeCount = 0;
if (L != NULL) {
LNode *p = L->next;
while(p != NULL) {
nodeCount++;
p = p->next;
}
}
return nodeCount;
}
bool InitList(LinkList &L) {
L = (LNode*)malloc(sizeof(LNode));
if (L == NULL) {
return false;
}
L->next = NULL;
return true;
}
void DesLinkList(LinkList &L) {
LNode* p = L->next;
while (p != NULL) {
LNode* p_free = p;
p = p->next;
free(p_free);
}
free(L);
L = NULL;
}
bool ListInsert(LinkList &L, int i, ElemType e) {
if (i < 1) return false;
LNode* p = L;
int j = 0;
while(p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL) {
return false;
}
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
int main() {
LinkList L;
InitList(L);
ListInsert(L, 1, 'A');
PrintElement(L);
DesLinkList(L);
int len = GetLinkListLen(L);
cout << "单链表的长度为: " << len << endl;
return 0;
}