1. 单链表结点表示
typedef struct LNode {
int data;
struct LNode* next;
}LNode,*LinkList;
2. 初始化单链表
bool InitList(LinkList &L) {
LNode* p = (LNode*)malloc(sizeof(LNode));
if (!p) {
printf("INITE FAIL\n");
return false;
}
p->next = NULL;
L = p;
return printf("INITE OK\n");
}
3. 创建单链表
3.1 头插法创建单链表
bool List_HeadInsert(LinkList& L, int len=0) {
if (len < 0) {
printf("ERROR:'len' < 0\n");
return false;
}
int data;
while (len ) {
LNode* p = (LNode*)malloc(sizeof(LNode));
if (!p) {
printf("HEAD INSERT FAIL\n");
return false;
}
printf("No.%d NODE VALUE:", len);
scanf_s("%d", &data);
p->data = data;
p->next = L->next;
L->next = p;
len--;
}
return printf("HEAD INSERT OK\n");
}
3.2 尾插法创建单链表
bool List_TailInsert(LinkList& L, int len = 0) {
if (len < 0) {
printf("ERROR:'Len' > 0\n");
return false;
}
int count = 1;
int data;
LNode* r = L;
while (len) {
LNode* p = (LNode*)malloc(sizeof(LNode));
if (!p) {
printf("TAIL INSERT FAIL\n");
return false;
}
printf("No.%d NODE VALUE:", count);
scanf_s("%d", &data);
count++;
p->data = data;
p->next = r->next;
r->next = p;
r = p;
len--;
}
return printf("TAIL INSERT OK\n");
}
4. 打印单链表
bool PrintList(LinkList L) {
if (!L->next) {
return printf("NULL LIST\n");
}
printf("LIST:Head");
LNode* p = L->next;
while (p) {
printf("->[%d]", p->data);
p = p->next;
}
return printf("\nPRINT OK\n");
}
5. 单链表的查找
5.1 按序号查找结点
LNode* GetElem(LinkList L, int i) {
if (i < 1) {
return NULL;
}
int j = 1;
LNode* p = L->next;
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
5.2 按值查找结点
LNode* LocateElem(LinkList L, int e) {
if (!L->next) {
return NULL;
}
LNode* p = L->next;
while (p !=NULL && p->data != e) {
p = p->next;
}
return p;
}
6. 求表长
int List_Length(LinkList L) {
LNode* p = L;
int count = 0;
while (p->next) {
p = p->next;
count++;
}
return count;
}
7. 插入结点
7.1 按位序插入结点
bool ListInsertNode(LinkList& L, int i,LNode *insertNode) {
if (i < 1) {
return false;
}
LNode* p = L;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (!p) {
return false;
}
else {
insertNode->next = p->next;
p->next = insertNode;
}
return true;
}
bool ListInsertData(LinkList& L, int i, int e) {
if (i < 1) {
return false;
}
LNode* p = L;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (!p) {
return false;
}
LNode* s = (LNode*)malloc(sizeof(LNode));
if (!s) {
return false;
}
else {
s->data = e;
s->next = p->next;
p->next = s;
}
return true;
}
8. 删除结点
8.1 按位序删除结点
bool ListInsertData(LinkList& L, int i, int e) {
if (i < 1) {
return false;
}
LNode* p = L;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (!p) {
return false;
}
LNode* s = (LNode*)malloc(sizeof(LNode));
if (!s) {
return false;
}
else {
s->data = e;
s->next = p->next;
p->next = s;
}
return true;
}