不带头结点的单链表
程序员文章站
2024-03-21 12:40:28
...
不带头结点的单链表是以一个指针来存储第一个结点的位置,相当于带头结点单链表的头结点只存储地址而不存储目前的结点个数。插入删除和带头结点的链表不一样外,其它功能基本相似。
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node, *List;
//单链表的初始化
void InitList(List *head)
{
assert(head != nullptr);
*head = nullptr;
}
//创建一个节点
Node* createNode(List head,int val)
{
Node *node = (Node *)malloc(sizeof(Node));
assert(node != nullptr);
node->data = val;
node->next = nullptr;
return node;
}
//头插
bool Insert_head(List *head, int val)
{
//Node *p = (Node *)malloc(sizeof(Node));
//p->data = val;
assert(head != nullptr);
Node *p = createNode(*head, val);
p->next = *head;
*head = p;
return true;
}
//尾插法
bool tailInsert(List *head, int val)
{
assert(head != nullptr);
Node *p = createNode(*head, val);
if (*head == nullptr)
{
*head = p;
return true;
}
Node *q;
for (q = *head; q->next != NULL; q = q->next);
{
//p->next = q->next;
q->next = p;
return true;
}
}
//找前驱
Node* FindPrior(List head, int pos) //找目标结点的前一个
{
List p = head;
while (pos - 1)
{
p = p->next;
pos--;
}
return p;
}
//长度
int length(List head)
{
//assert(head != nullptr);
List cur = head;
int count = 0;
while (cur != nullptr)
{
count++;
cur = cur->next;
}
return count;
}
//任意位置插入
bool Insert(List *head, int val,int pos)
{
assert(head != nullptr);
if (pos<0 || pos>length(*head))
return false;
if (pos == 0)
{
if (Insert_head(head, val))
return true;
}
List p = FindPrior(*head, pos);
List q = createNode(*head,val);
q->next = p->next;
p->next = q;
return true;
}
//删除任意节点
bool Delete(List *head, int pos)
{
assert(head != nullptr);
if (pos<0 || pos>length(*head))
return false;
List p = FindPrior(*head, pos);
List q = p->next;
p->next = q->next;
free(q);
q = nullptr;
return true;
}
//逆置
void reserve(List *head)
{
assert(*head != nullptr);
List cur = *head;
List pnext = cur;
*head = nullptr;
while (cur != nullptr)
{
pnext = cur->next;
cur->next = *head;
*head = cur;
cur = pnext;
}
}
//打印
void Show(List *head)
{
assert(head != nullptr);
List p = *head;
while (p != nullptr)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//删除
void destory(List *head)
{
Node *cur = *head;
Node *pnext = cur;
while (cur != nullptr)
{
pnext = cur->next;
free(cur);
cur = pnext;
}
*head = nullptr;
}
int main()
{
List head;
InitList(&head);
for (int i = 0; i < 10; i++)
{
tailInsert(&head, i);
}
Show(&head);
Insert(&head,33,5);
Show(&head);
Delete(&head, 3);
reserve(&head);
Show(&head);
int len = length(head);
printf("%d\n",len);
destory(&head);
return 0;
}