数据结构单链表的增删查改(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 = https://www.it610.com/article/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 =https://www.it610.com/article/= x) { return cur; } else { cur = cur->next; } } return NULL; }

【数据结构单链表的增删查改(c语言实现)】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; }

    推荐阅读