【单链表】 c语言的单链表
单链表:是一种线性表,每个节点里面存储着下一个节点的指针,把存储的数据元素连起来。
本文中应用了C++的引用来传参数。

存储结构:
typedef int DataType;
typedef struct SListNode
{DataType _data;struct SListNode* _next; //指向下一个节点
}SListNode; 链表中节点的建立与销毁:
SListNode* _BuyNode(DataType x) //建立节点
{
SListNode* tmp =(SListNode*) malloc(sizeof(SListNode));
tmp->_data = x;
tmp->_next = NULL;
return tmp;
}
void DestorySList(SListNode*& pHead) //销毁节点
{
SListNode* cur = pHead;
while (cur)
{
SListNode* tmp = cur;
cur = cur->_next;
free(tmp);
}
pHead = NULL;
}
// 单链表的 增 删 查 ///
#include
#includetypedef int DataType;
typedef struct SListNode
{DataType _data;struct SListNode* _next; //指向下一个节点
}SListNode;//void PushBack(SListNode*& pHead, DataType x);
//void PopBack(SListNode*& pHead);
//void PushFront(SListNode*& pHead, DataType x);
//void PopFront(SListNode*& pHead);
//SListNode* Find(SListNode* pHead, DataType x);
//void Insert(SListNode* pos, DataType x);
//void Erase(SListNode*& pHead, SListNode* pos);
//void DestorySList(SListNode*& pHead);
//void PrintSlist(SListNode* pHead);SListNode* _BuyNode(DataType x) //建立节点
{SListNode* tmp =(SListNode*) malloc(sizeof(SListNode));tmp->_data = x;tmp->_next = NULL;return tmp;
}
void DestorySList(SListNode*& pHead) //销毁节点
{SListNode* cur = pHead;while (cur){SListNode* tmp = cur;cur = cur->_next;free(tmp);}pHead = NULL;
}
void PrintSlist(SListNode* pHead)
{SListNode* cur = pHead;while (cur){printf("%d->", cur->_data);cur = cur->_next;}printf("NULL\n");
}void PushBack(SListNode*& pHead, DataType x) //尾插
{//1.空 2.不为空if (pHead == NULL){pHead = _BuyNode(x);}else{ //找尾节点SListNode* tail = pHead;while (tail->_next){tail = tail->_next;}tail->_next = _BuyNode(x);}
}void PopBack(SListNode*& pHead)
{//空;一个节点;两个及以上节点if (pHead == NULL){return;}else if (pHead->_next == NULL){free(pHead);pHead = NULL;}else{SListNode* tail = pHead;SListNode* prev = NULL;while (tail->_next){prev = tail;tail = tail->_next;}free(tail);prev->_next = NULL;}
}
void PushFront(SListNode*& pHead, DataType x) //头插
{if (pHead == NULL)pHead = _BuyNode(x);else{SListNode* tmp = _BuyNode(x);tmp->_next = pHead;pHead = tmp;}
}
void PopFront(SListNode*& pHead)
{if (pHead== NULL)return;else if (pHead->_next == NULL){free(pHead);pHead = NULL;}else{SListNode*tmp = pHead;pHead = pHead->_next;free(tmp);}
}SListNode* Find(SListNode* pHead, DataType x) //查
{SListNode* cur = pHead;while (cur){if (cur->_data == x)return cur;cur = cur->_next;}printf("链表中无此数据\n");return NULL;
}
void Insert(SListNode* pos, DataType x) //增加节点
{assert(pos);SListNode* tmp = _BuyNode(x);tmp->_next = pos->_next;pos->_next = tmp;
}
void Erase(SListNode*& pHead, SListNode* pos) //删除
{assert(pos);if (pos == pHead){pHead = pHead->_next;free(pos);return; }SListNode* prev = pHead;while (prev){if (prev->_next == pos){prev->_next = pos->_next;free(pos);break;}prev = prev->_next;}
} 转载于:https://blog.51cto.com/1536262434/1753811
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
