链表基础操作实现

实现内容:
1、头插节点
2、尾插节点
3、头删节点元素
4、尾删节点元素
5、指定位置后插入节点元素
6、指定位置后删除节点元素
7、查找某个节点元素
8、清空链表
实现一:
创建节点结构体和链表结构体

typedef int Type;
//节点结构体
typedef struct Node {
 Type data;
 struct Node* next;
}Node;
//链表结构体:存放节点元素
typedef struct Slist {
 Node* _head;
}Slist;
//创建节点元素函数
Node* BuySListNode(Type x) {
 Node* sl = (Node*)malloc(sizeof(Node)) ;
 sl->data = x;
 sl->next = NULL;
 return sl;
}

实现二:
初始化链表、头插、尾插、打印的实现:

//初始化
void SListInit(Slist* plist) {
 plist->_head = NULL;
}
// 单链表打印
void SListPrint(Slist* plist){
 Node* s = plist->_head;
 while (s) {
  printf("%d  ", s->data);
  s = s->next;
 }
 printf("\n");
}
// 单链表尾插
void SListPushBack(Slist* pplist, Type x) {
 //创建节点元素
 Node* node = BuySListNode(x);
 //如果是空表
 if (pplist->_head == NULL) {
  pplist->_head = node;
  node->next = NULL;
 }
 //表里有元素
 else {
  Node* cur = pplist->_head;
  while (cur->next) {
   cur = cur->next;
  }
  cur->next = node;
  node->next = NULL;
 } 
}
// 单链表的头插
void SListPushFront(Slist* pplist, Type x) {
 Node* node = BuySListNode(x);
 //空表插入
 if (pplist->_head == NULL) {
  pplist->_head = node;
 }
 //有元素状况
 else {
  node->next = pplist->_head;
  pplist->_head = node;
 }
}

实现三:
头删、尾删的实现;

// 单链表的尾删
void SListPopBack(Slist* pplist) {
 Node* pre = NULL;
 Node* tail = pplist->_head;
 //1、空或者只有一个节点
 //2、两个及以上各节点
 if (tail == NULL || tail->next == NULL) {
  free(tail);
  pplist->_head = NULL;
 }
 else {
  while (tail->next) {
   pre = tail;
   tail = tail->next;
  }
  free(tail);
  tail = NULL;
  pre->next = NULL;
 }
}
// 单链表头删
void SListPopFront(Slist* pplist) {
 //没有元素则不操作,否则依次删
 if (pplist->_head) {
  Node* cur = pplist->_head;
  pplist->_head = pplist->_head->next;
  free(cur);
  cur = NULL;
 }
}

实现四:
指定位置后插入、删除节点元素实现:

// 单链表在pos位置之后插入x
void SListInsertAfter(Node* pos, Type x){
 assert(pos);
 Node* next = pos->next;
 Node* newNode = BuySListNode(x);
 pos->next = newNode;
 newNode->next = next;
}
// 单链表删除pos位置之后的值
void SListEraseAfter(Node* pos) {
 //必须有两个及以上的节点元素
 assert(pos && pos->next);
 Node* next = pos->next;
  pos->next = next->next;
  free(next);
  next = NULL;
}

实现五:
查找、清空操作的实现:

Node* SListFind(Slist* plist, Type x) {
 Node* cur = plist->_head;
 while (cur) {
  if (cur->data == x) {
   return cur;
  }
  cur = cur->next;
 }
 return NULL;
}
// 单链表的销毁
void SListDestory(Slist* plist) {
 while(plist->_head) {
  Node* cur = plist->_head;
  plist->_head = plist->_head->next;
  free(cur);
  cur = NULL;
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值