用C语言简单实现
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType; //让链表存储数据为int,如果想泛化能力更强,可以采用C++的模板技术
typedef struct Node
{
ElemType data;
Node* next;
}*PNode;
//初始化链表
bool InitPNode(PNode& L)
{
L = (Node*)malloc(sizeof(Node));
if (L == NULL)
{
return false;
}
L->next = NULL;
return true;
}
//利用数组初始化链表(头插法)
void CreateListH(PNode&L,ElemType A[],int A_size)
{
int i = 0;
for (i;i<A_size;++i)
{
PNode temp = (PNode)malloc(sizeof(Node));
temp->data = A[i];
temp->next = L->next;
L->next = temp;
}
}
//利用数组初始化链表(尾插法)
void CreateListT(PNode& L, ElemType A[], int A_size)
{
PNode T = L;
while (T->next != NULL)
{
T = T->next;
}
int i = 0;
for (i; i < A_size; ++i)
{
PNode temp = (PNode)malloc(sizeof(Node));
temp->data = A[i];
T->next = temp;
T = temp;
T->next = NULL;
}
}
//打印链表
void PrintList(PNode& L)
{
if (L == NULL)
return;
PNode temp = L->next;
while (temp != NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
//返回链表当前的长度
int reListLength(PNode& L)
{
int i = 0;
PNode temp = L->next;
while (temp != NULL)
{
++i;
temp = temp->next;
}
return i;
}
//第i号位置插入元素 e,若i位置不符合要求,返回false
bool InsertI(PNode& L, int i, ElemType e)
{
if (i<1 || i>reListLength(L))
return false;
PNode T = L;
int j = 1;
while (j<i) //跑到i-1位置
{
T = T->next;
++j;
}
PNode temp = (PNode)malloc(sizeof(Node));
temp->data = e;
temp->next = T->next;
T->next = temp;
return true;
}
//删除第i号位置的元素
bool DeleteI(PNode&L,int i)
{
if (i<1 || i>reListLength(L))
return false;
PNode T = L;
int j = 1;
while (j < i)
{
T = T->next;
++j;
}
PNode q = T->next;
T->next = q->next;
free(q);
return true;
}
//删除整个链表
bool DeleteL(PNode&L)
{
if (L == NULL)
{
return false; //链表本身为空,返回false表示未执行删除操作
}
while (L->next!=NULL)
{
PNode temp = L->next;
L->next = temp->next;
free(temp);
}
return true;
}
int main()
{
PNode L; //L为头结点,不含数据
if (InitPNode(L))
{
printf("链表初始化成功!\n");
}
printf("链表长度为:%d\n", reListLength(L));
int A[5] = {1,2,3,4,5};
//CreateListH(L,A,5);
CreateListT(L, A, 5);
PrintList(L);
printf("链表长度为:%d\n", reListLength(L));
InsertI(L,5,6);
PrintList(L);
printf("链表长度为:%d\n", reListLength(L));
DeleteI(L,6);
PrintList(L);
printf("链表长度为:%d\n", reListLength(L));
if (DeleteL(L))
{
printf("删除链表成功");
}
PrintList(L);
printf("链表长度为:%d\n", reListLength(L));
return 0;
}