链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。因此我们可以通过结构体,结构体指针来实现一个单链表,包括基本的增删查改。注:(所有给出的操作均保证有解且合法)。
1.链表的初始化
typedef struct ListNode
{
int data; //数据域
struct ListNode *next; //指针域
}node; //定义结构体
node *L = NULL; //头指针
node *T = NULL; //尾指针
void Init()
{
L = (node*)malloc(sizeof(node));
T = (node*)malloc(sizeof(node));
}
2.链表的头插法
void To_HeadListNode(int x) //将元素x插入链表中
{
node *p = (node*)malloc(sizeof(node));
p->data = x;
p->next = L->next;
L->next = p;
}
3.链表的尾插法
void To_TailListNode(int x) //将元素x插入链表中
{
node *p = (node*)malloc(sizeof(node));
if(L->next == NULL) L->next = p;
T->next = p;
p->data = x;
p->next = NULL;
T = p;
}
4.按位插入
void Insert(int k, int x) //在第k个结点后插入x
{
node *p = (node*)malloc(sizeof(node));
node *t = L;
while(k--)
{
t = t->next;
}
p->data = x;
p->next = t->next;
t->next = p;
}
5.查找
(1)找到第k个结点的值
int Findvalue(int k)
{
node *p = L;
while(k--)
{
p = p->next;
}
return p->data;
}
(2)查找值为x的结点下标
int FindIndex(int x)
{
node *p = L;
int j = 0;
while(p != NULL && p->data != x)
{
p = p->next;
j++;
}
return j;
}
6.删除
void Delete(int k) //删除第k个结点后的结点
{
node *t = L;
while(k--)
{
t = t->next;
}
node *p = t->next;
t->next = t->next->next;
free(p);
}
7.遍历
void Print() //链表的遍历
{
node *p = L->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}