#include"list.h"
#include<malloc.h>
#include<assert.h>
#include<stdio.h>
SListNode* BuySListNode(SLDataType data)
{
SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
if (NULL ==newNode)
{
assert(0);//调试宏,参数为0触发,非0不会触发
return NULL;
}
newNode->next = NULL;
newNode->data = data;
return newNode;
}
void SListPushBack(SListNode** head, SLDataType data)
{
assert(head);
SListNode* newNode = BuySListNode(data);
//空链表
if (NULL == *head)
{
*head = newNode;
}
else
{
//找到链表最后一个节点
SListNode* cur = *head;
while (cur->next)
{
cur = cur->next;//cur++
}
//插入新节点
cur->next = newNode;
}
}
void SListPopBack(SListNode** head)
{
assert(head);//检测非法情况
if (NULL == *head)
{
//空链表
return;
}
else
{
//链表至少有一个节点
SListNode* cur = *head;
SListNode* prev = NULL;
while (cur->next)
{
prev = cur;
cur = cur->next;
}
//最后节点找到,删除节点
free(cur);
}
}
void SListPushfront(SListNode** head, SLDataType data)
{
assert(head);
SListNode* newNode = BuySListNode(data);
newNode->next = *head;
*head = newNode;
空链表
//if (NULL == *head)
//{
// *head = newNode;
//}
链表有多个节点
//else
//{
// newNode->next = *head;
// *head = newNode;
//}
}
void SListPopfront(SListNode** head)
{
assert(head);
if (NULL == *head)
{
return NULL;
SListNode* delNode = *head;
*head = delNode->next;
free(delNode);
}
}
void SListInsertafter(SListNode* pos, SLDataType data)
{
if (NULL == pos)
return;
SListNode* newNode = BuySListNode(data);
newNode->next = pos->next;
pos->next = newNode;
}
void SListEraseafter(SListNode* pos)
{
if (NULL == pos)
return;
SListNode* delNode = pos->next;
pos->next = delNode->next;
free(delNode);
}
int SListNodeSize(SListNode* head)
{
SListNode* cur = head;
int count = 0;
while (cur)
{
count++;
cur = cur->next;
}
return count;
}
int SListEmpty(SListNode* head)
{
return NULL == head;
}
SListNode* SListFind(SListNode* head, SLDataType data)
{
SListNode* cur = head;
while (cur)
{
if (cur->data == data)
return cur;
cur = cur->next;
}
return NULL;
}
void SListDestroy(SListNode** head)
{
assert(head);
while (*head)
{
SListNode* delNode = *head;
*head = delNode->next;
free(delNode);
}
}
void PrintSList(SListNode* head)
{
SListNode* cur = head;
while (cur)
{
printf("%d--->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
链表的实现
最新推荐文章于 2022-10-16 16:14:18 发布