单链表基础实现
结点申请
在链表中增加数据需要申请一个新的结点。首先定义数据类型 SLDatatype,结构体名称为 SL。申请新结点的函数如下:
SLDatatype* SLBuyNode(SLDatatype x) {
SL* node = (SL*)malloc(sizeof(SL));
if (node == NULL) {
perror("malloc fail!");
exit(1);
}
node->data = x;
node->next = NULL;
return node;
}
尾插
尾插即向链表尾部添加元素。需要先找到最后一个结点,将新结点链接到其后。

// 尾插函数
void SLPushBack(SL** pphead, SLDatatype x) {
// 申请新结点
SL* newnode = SLBuyNode(x);
if (*pphead == NULL) {
*pphead = newnode;
} else {
// 找尾结点
SL* pcur = *pphead;
while (pcur->next) {
pcur = pcur->next;
}
pcur->next = newnode;
}
}
void SLTest() {
SL* plist = NULL;
SLPushBack(&plist, 1);
// 假设存在打印函数
// SLPrint(plist);
SLPushBack(&plist, 2);
SLPushBack(&plist, 3);
// SLPrint(plist);
}
int main() {
SLTest();
;
}


