typedef int SLTDataType;
//定义一个链表节点
typedef struct SListNode
{
SLTDataType data; //数据
struct SListNode* next; //指针,指向下一个节点
}SLTNode;
//单链表尾插
void SListPushBack(SLTNode** phead, SLTDataType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
if (newnode == NULL)
{
printf("malloc fail\n");
return;
}
newnode->data = x;
newnode->next = NULL;
if (*phead == NULL)
{
*phead = newnode;
}
else
{
SLTNode* tail = *phead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
//单链表的头插
void SListPushFront(SLTNode** phead, SLTDataType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
if (newnode == NULL)
{
printf("malloc fail\n");
return;
}
newnode->data = x;
newnode->next = NULL;
newnode->next = *phead;
*phead = newnode;
}
//单链表的尾删
void SListPopBack(SLTNode** phead)
{
// assert(*phead != NULL); //断言,不满足条件会报错
if ((*phead)->next == NULL)
{
free(*phead);
*phead = NULL;
}
else
{
SLTNode* tail = *phead;
while (tail->next->next)
{
tail = tail->next;
}
free(tail->next);
tail->next = NULL;
}
}
//单链表头删
void SListPopFornt(SLTNode** phead)
{
// assert(*phead != NULL);
SLTNode* next = (*phead)->next;
free(*phead);
*phead = next;
}
//打印链表
void SListPrint(SLTNode* phead)
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d-> ", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
//单链表查找
SLTNode* SListFind(SLTNode* phead, SLTDataType x)
{
SLTNode* cur = phead;
while (cur)
{
if (cur->data == x)
{
return cur;
}
else
{
cur = cur->next;
}
}
return NULL;
}
//单链表在pos位置之前插入x
void SListInsert(SLTNode** phead, SLTNode* pos, SLTDataType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
if (newnode == NULL)
{
printf("malloc fail\n");
return;
}
newnode->data = x;
newnode->next = NULL;
if (*phead == pos)
{
newnode->next = *phead;
*phead = newnode;
}
else
{
//找到pos的前一个位置
SLTNode* posPrev = *phead;
while (posPrev->next != pos)
{
posPrev = posPrev->next;
}
posPrev->next = newnode;
newnode->next = pos;
}
}
//单链表删除pos位置的值
void SListErase(SLTNode** phead, SLTNode* pos)
{
if (*phead == pos)
{
*phead = pos->next;
free(pos);
}
else
{
SLTNode* prev = *phead;
while (prev->next != pos)
{
prev = prev->next;
}
prev->next = pos->next;
free(pos);
}
}
测试:
void listTest(void)
{
SLTNode* phead = NULL;
printf("尾插:");
SListPushBack(&phead, 1);
SListPushBack(&phead, 2);
SListPushBack(&phead, 3);
SListPrint(phead);
printf("头插:");
SListPushFront(&phead, 4);
SListPushFront(&phead, 5);
SListPrint(phead);
printf("尾删:");
SListPopBack(&phead);
SListPrint(phead);
printf("头删:");
SListPopFornt(&phead);
SListPrint(phead);
printf("在1前插入6:");
SLTNode* find = SListFind(phead, 1);
SListInsert(&phead, find, 6);
SListPrint(phead);
printf("删除1:");
find = SListFind(phead, 1);
SListErase(&phead, find);
SListPrint(phead);
}