单链表的简单实现
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef int ElemType,Status;
typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode,*LinkList;
//初始化链表
bool InitList(LinkList &L) {
L = (LNode *)malloc(sizeof(LNode));
if(!L) return false; //如果申请内存失败,返回false
L->next = NULL;
return true;
}
//头插法(逆序插入)
bool List_headinsert(LinkList &L) {
LNode *s;
for (int i = 1; i < 10; i++)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = i;
s->next = L->next;
L->next = s;
}
return true;
}
//尾插法(顺序插入)
bool List_tailinsert(LinkList &L) {
LNode *r,*p;
p = L;
for(int i = 1; i < 10; i++) {
r = (LNode *)malloc(sizeof(LNode));
r->data = i;
p->next = r;
p = r;
}
p->next = NULL;
return true;
}
//单链表的输出
bool List_out(LinkList L) {
LNode *p = L->next;
while (p)
{
printf("%d ",p->data);
p = p->next;
}
return true;
}
//单链表的长度
bool List_length(LinkList L, ElemType &length) {
LNode *p = L;
int j = 0;
while (p->next)
{
p = p->next;
j++;
}
length = j;
return true;
}
//单链表的按值查找
bool Locate_List(LinkList L, ElemType e, ElemType &m) {
LNode *p = L;
int j = 0;
while (p != NULL && p->data != e)
{
p = p->next;
j++;
}
if (!p)
{
return false;
}
m = j;
return true;
}
//单链表的按位查找
bool Getelem_List(LinkList L, int i, ElemType &e) {
if(i < 1) return false;
LNode *p = L;
int j = 0;
while (p != NULL && j < i)
{
p = p->next;
j++;
}
if(!p) return false;
e = p->data;
return true;
}
//单链表的插入
bool List_insert(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) return false;
LNode *s;
s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
//单链表的删除
bool List_delete(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) return false;
if(!p->next) return false;
LNode *s = p->next;
e = s->data;
p->next = s->next;
free(s);
return true;
}
int main() {
LinkList L;
LinkList K;
InitList(L);
InitList(K);
List_headinsert(L);
printf("请输出链表L中的数:\n");
List_out(L);
printf("\n");
List_tailinsert(K);
printf("请输出链表K中的数:\n");
List_out(K);
printf("\n");
ElemType Llength;
List_length(L, Llength);
printf("链表L的长度为:%d\n", Llength);
ElemType Klength;
List_length(K, Klength);
printf("链表L的长度为:%d\n", Klength);
ElemType Lm;
Locate_List(L, 6, Lm);
printf("6 在L表中的第 %d 位\n", Lm);
ElemType Km;
Locate_List(K, 6, Km);
printf("6 在K表中的第 %d 位\n", Km);
ElemType Ln;
Getelem_List(L, 3, Ln);
printf("L表中第3位的值为 %d\n", Ln);
ElemType Kn;
Getelem_List(K, 3, Kn);
printf("K表中第3位的值为 %d\n", Kn);
ElemType Le = 13;
List_insert(L, 3, Le);
printf("请输出链表L中的数:\n");
List_out(L);
printf("\n");
ElemType Ke = 13;
List_insert(K, 3, Ke);
printf("请输出链表K中的数:\n");
List_out(K);
printf("\n");
ElemType Lh;
List_delete(L, 8, Lh);
printf("请输出链表L中的数:\n");
List_out(L);
printf("\n");
printf("Lh = %d\n",Lh);
ElemType Kh;
List_delete(K, 8, Kh);
printf("请输出链表K中的数:\n");
List_out(K);
printf("\n");
printf("Kh = %d\n",Kh);
}