单链表原理就是定义一个结构体,结构体中有自身属性和一个自身类型的指针,将该指针指向下一个结构体对象,用以模拟链表的操作
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef int bool;
typedef int ElemType;//在这里修改处理元素的类型
typedef struct Node
{
ElemType num;
struct Node* next;
}Node;
//初始化单链表
void InitList(int nums, Node *L)
{
Node *link1, *link2;
int i;
L = (Node*)malloc(sizeof(Node));
link1 = (Node*)malloc(sizeof(Node));
L->next = link1;
for(i = 0; i < nums; i++)
{
int n;
scanf("%d", &n);
link2 = (Node*)malloc(sizeof(Node));
link2->num = n;
link1->next = link2;
link1 = link2;
}
link1->next = NULL;
}
//验证该链表是否为空
bool ListEmpty(Node L)
{
if(L->next)
{
return true;
}
return false;
}
//清空单链表
void ClearList(Node *L)
{
Node *mid, *key;
mid = L->next;
while(mid)
{
key = mid->next;
free(mid);
mid = key;
}
}
//获取链表某个位置上的元素
bool GetElem(Node L, int i, ElemType* num)
{
int j = 1;
Node* mid = L.next;
while(j < i&& mid)
{
mid = mid->next;
j++;
}
if(j > i|| !mid)
{
return false;
}
*num = mid->num;
return true;
}
//定位某元素在链表的位置
int LocateELem(Node L, ElemType e)
{
int pos = 1;
Node *mid = L.next;
while(mid)
{
if(mid->num == e)
{
return pos;
}
mid = mid->next;
pos++;
}
return 0;
}
//将某个元素插入到链表的某个位置上
bool ListInsert(Node* L, int i, ElemType e)
{
int j = 1;
Node *mid, *key;
mid = L->next;
while(j < i&& mid)
{
j++;
mid = mid->next;
}
if(j > i|| !mid)
{
return false;
}
key = (Node*)malloc(sizeof(Node));
key->num = e;
key->next = mid->next->next;
mid->next = key;
return true;
}
//删除线性表中某位置的元素
bool ListDelete(Node *L, int i,ElemType *e)
{
int j = 1;
Node *mid = L->next;
while(j < i - 1&& mid)
{
j++;
mid = mid->next;
}
if(j > i|| !mid)
{
return false;
}
Node *key = mid->next;
mid->next = mid->next->next;
free(key);
return true;
}
//显示线性表元素个数
int ListLength(Node L)
{
int j = 1;
Node* mid = L.next;
while(mid)
{
j++;
mid = mid->next;
}
return j;
}
//合并两个有序链表(元素排列顺序相同)
Node* ListMerge(Node* L, Node* LL)
{
Node* L1 = L->next;
Node* L2 = LL->next;
Node* L3 = (Node*)malloc(sizeof(Node));
Node* mid = NULL;
L3->next = mid;
while(L1&& L2)
{
if(L1->num < L2->num)
{
mid = L1;
L1 = L1->next;
mid = mid->next;
}
else
{
mid = L2;
L2 = L2->next;
mid = mid->next;
}
}
while(L1)
{
mid = L1;
L1 = L1->next;
mid = mid->next;
}
while(L2)
{
mid = L2;
L2 = L2->next;
mid = mid->next;
}
L1->next = NULL;
L2->next = NULL:
L3->next = NULL:
return L3;
}