一、实现单链表
1. 链表节点查找
在链表中查找节点是基础操作,核心目标是根据指定条件(如值匹配)定位目标节点。本函数以值匹配作为条件。
函数形式:
SListNode* SLTFind(SListNode* h, type x)
代码实现:
SListNode* SLTFind(SListNode* h, type x) {
SListNode* p = h;
while (p) {
if (p->data == x) {
return p;
}
p = p->next;
}
return NULL;
}
讲解:
- 参数:
SListNode* h指向单链表头节点的指针;type x为要查找的值。 - 返回值:找到则返回节点指针,未找到返回
NULL。 - 逻辑:遍历链表,比较当前节点数据与目标值,相等则返回,否则继续。
2. 链表在指定位置之前或之后插入元素
(1)链表在指定位置之前插入元素
函数形式:
void SLTInsert(SListNode** h, SListNode* pos, type x)
代码实现:
void SLTInsert(SListNode** h, SListNode* pos, type x) {
if (h == NULL || pos == NULL || *h == NULL) {
printf("前插入失败\n");
return;
}
if (*h == pos) {
SLTPushFront(h, x);
return;
}
SListNode* p = *h;
(p != && p->next != pos) {
p = p->next;
}
(p) {
SListNode* newnode = (x);
newnode->next = pos;
p->next = newnode;
} {
();
;
}
}


