一、创建一个结点
typedef int SLTType;
typedef struct SLTnode
{
SLTType data;
struct SLTNode* next;
}SLTNode;
二、创建一个链表
//开辟空间
SLTNode* n1 = (SLTNode*)malloc(sizeof(SLTNode));
assert(n1);
SLTNode* n2 = (SLTNode*)malloc(sizeof(SLTNode));
assert(n2);
SLTNode* n3 = (SLTNode*)malloc(sizeof(SLTNode));
assert(n3);
SLTNode* n4 = (SLTNode*)malloc(sizeof(SLTNode));
assert(n4);
//给链表赋值
n1->data = 1;
n2->data = 2;
n3->data = 3;
n4->data = 4;
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = NULL;
SLTNode* SList = NULL;
三、打印链表
void SLTprint(SLTNode* phead)
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
四、开辟一个新的结点
SLTNode* SLTCreat(SLTType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
assert(newnode);
newnode->data = x;
newnode->next = NULL;
return newnode;
}
五、尾插
void SLTPushBack(SLTNode** phead, SLTType x)
{
assert(phead);
SLTNode*newnode=SLTCreat(x);
SLTNode* tail = *phead;
if (*phead == NULL)
{
*phead = newnode;
}
else
{
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
六、头插
void SLTPushFront(SLTNode** phead, SLTType x)
{
assert(phead);
SLTNode* newnode = SLTCreat(x);
newnode->next = *phead;
*phead = newnode;
}
七、尾删
void SLTPopBack(SLTNode** phead)
{
assert(phead);
assert(*phead);
SLTNode* tail = *phead;
SLTNode* retail = NULL;
if ((*phead)->next == NULL)
{
*phead = NULL;
}
else
{
while (tail->next != NULL)
{
retail = tail;
tail = tail->next;
}
free(tail);
retail->next = NULL;
}
}
八、头删
void SLTPopFront(SLTNode** phead)
{
assert(phead);
assert(*phead);
SLTNode* x = *phead;
*phead = (*phead)->next;
free(x);
}
九、查找
SLTNode* SLTFind(SLTNode* phead, SLTType x)
{
SLTNode* cur = phead;
while (cur != NULL)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
十、插入
SLTNode* SLTInsert(SLTNode** phead, SLTNode* pos, SLTType x)
{
assert(pos);
assert(phead);
if (pos == *phead)
{
SLTPushFront(phead, x);
}
else
{
SLTNode* newnode = SLTCreat(x);
SLTNode* cur = *phead;
while (cur -> next != pos)
{
cur = cur->next;
}
cur->next = newnode;
newnode->next = pos;
}
}
十一、删除
SLTNode* SLTDele(SLTNode** phead, SLTNode* pos)
{
assert(phead);
assert(*phead);
if (pos == *phead)
{
SLTPopFront(phead);
}
else
{
SLTNode* cur = *phead;
while (cur->next != pos)
{
cur = cur->next;
}
cur->next = pos->next;
free(pos);
}
}
总结
看到这里不要以为就结束了,赶快点击到下一章的习题练习检验自己会不会吧!!
如果觉得浩克写的还不错的话,记得关注浩克奥,我们一起努力!