数据结构单链表的增删查改(c语言实现)

1、单链表

typedef int SLTDataType;
typedef struct SListNode
{
 SLTDataType data; // val
 struct SListNode* next;
}SListNode;

2、动态申请一个结点

SListNode* BuySListNode(SLTDataType x)
{
 SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
 newNode->data = x;
 newNode->next = NULL;
 return newNode;
}

3、单链表打印

void SListPrint(SListNode* pList)
{
 SListNode* cur = pList;
 while (cur != NULL)
 {
  printf("%d->", cur->data);
  cur = cur->next;
 }
 printf("NULL\n");
}

4、单链表尾插

void SListPushBack(SListNode** ppList, SLTDataType x)
{
 SListNode* newNode = BuySListNode(x);
 if (*ppList == NULL)
 {
  *ppList = newNode;
 }
 else
 {
  SListNode* tail = *ppList;
  while (tail->next != NULL)
  {
   tail = tail->next;
  }
  tail->next = newNode;
 }
}

5、单链表头插

void SListPushFront(SListNode** ppList, SLTDataType x)
{
 SListNode* newNode = BuySListNode(x);
 newNode->next = *ppList;
 *ppList = newNode;
}

6、单链表尾删

void SListPopBack(SListNode** ppList)
{
 // 1.空
 // 2.只有一个节点
 // 3.有多个节点
 if (*ppList == NULL)
 {
  return;
 }
 else if ((*ppList)->next == NULL)
 {
  free(*ppList);
  *ppList = NULL;
 }
 else
 {
  SListNode* prev = NULL;
  SListNode* tail = *ppList;
  while (tail->next != NULL)
  {
   prev = tail;
   tail = tail->next;
  }
  free(tail);
  if (prev != NULL)
   prev->next = NULL;
 }
}

7、单链表头删

void SListPopFront(SListNode** ppList)
{
 if (*ppList)
 {
  SListNode* next = (*ppList)->next;
  free(*ppList);
  *ppList = next;
 }
}

8、单链表查找

SListNode* SListFind(SListNode* pList, SLTDataType x)
{
 SListNode* cur = pList;
 while (cur)
 {
  if (cur->data == x)
  {
   return cur;
  }
  else
  {
   cur = cur->next;
  }
 }
 return NULL;
}

9、单链表在pos位置之后插入x

void SListInsertAfter(SListNode* pos, SLTDataType x)
{
 ListNode* newnode = BuySListNode(x);
 pos->next = newnode;
 newnode->next = pos->next;
}

10、单链表删除pos位置之后的值x

void SListEraseAfter(SListNode* pos)
{
 SListNode* next = pos->next;
 if (next != NULL)
 {
  pos->next = next->next;
  free(next);
 }
}

11、单链表的销毁

void SListDestory(SListNode** pplist)
{
 SListNode* cur = *pplist;
 while (cur)
 {
  SListNode* next = cur->next;
  free(cur);
  cur = next;
 }
 *pplist = NULL;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值