一、代码描述
c语言 顺序表中单链表的基本操作
初始化 打印 插入 头插 头删 尾插 尾删 查询
二、参考代码
#include<stdio.h>
#include<stdlib.h>
typedef int SLTDataType;
typedef struct SListNode
{
SLTDataType data;
struct SListNode* next;
}SLTNode;
SLTNode* Creatnewnode(SLTDataType x) {
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
if (newnode == NULL) {
printf("malloc fail");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
return newnode;
}
void SListpri(SLTNode* phead)//打印
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("\n");
}
void SListPushBack(SLTNode** pphead, SLTDataType x)//尾插,改变一级指针的内容,要传递二级指针
{
//创建新节点存储新数据
SLTNode* newnode = Creatnewnode(x);
if (*pphead == NULL) {
*pphead = newnode;
}
else{
//找尾节点
SLTNode* tail = *pphead;
while (tail->next != NULL)
{
tail = tail->next;
}
//连接
tail->next = newnode;
}
}
void SListPushFront(SLTNode** phead, SLTDataType x)//头插
{
SLTNode* newnode = Creatnewnode(x);
newnode->next = *phead;
*phead = newnode;
}
void SListPopFront(SLTNode** phead)//头删
{
/*if (*phead == NULL) {//空
return;
}
if ((*phead)->next == NULL) {//一个
free(*phead);
phead = NULL;
}
else
{//一个以上
SLTNode* first = *phead;
SLTNode* second = first->next;
free(first);
*phead = second;
}*/
if (*phead == NULL) {
printf("NULL");
}
else {
SLTNode* next = (*phead)->next;
free(*phead);
*phead = next;
}
}
void SListPopBack(SLTNode** phead)//尾删1.一个以上的节点2.空3.一个节点
{
if (*phead == NULL) {//空
return;
}
if ((*phead)->next == NULL) {//一个
free(*phead);
phead = NULL;
}
else
{//一个以上
SLTNode* pre = NULL;
SLTNode* tail = *phead;
while (tail->next)
{
pre = tail;
tail = tail->next;
}
free(tail);
tail = NULL;
pre->next = NULL;
}
}
SLTNode* SListFind(SLTNode* phead, SLTDataType x)//查询
{
SLTNode* cur = phead;
while (cur)
{
if (cur->data == x) {
return cur;
}
else
{
cur = cur->next;
}
}
return NULL;
}
void SListInsert(SLTDataType** pphead, SLTNode* pos, SLTDataType x)//插入(默认删除pos位置前面的那一个节点)配合查找使用
{
SLTNode* newnode = Creatnewnode(x);
if (*pphead == pos) {
newnode->next = *pphead;
*pphead = newnode;
}
else
{
SLTNode* posPre = *pphead;
while (posPre->next != pos)
{
posPre = posPre->next;
}
posPre->next = newnode;
newnode->next = pos;
}
}
int main() {
SLTNode* plist = NULL;
printf("尾插\n");
SListPushBack(&plist, 1);
SListPushBack(&plist, 2);
SListPushBack(&plist, 2);
SListPushBack(&plist, 2);
SListPushBack(&plist, 3);
SListPushBack(&plist, 4);
SListpri(plist);
printf("头插\n");
SListPushFront(&plist, 0);
SListpri(plist);
printf("尾删\n");
SListPopBack(&plist);
SListpri(plist);
printf("头删\n");
SListPopFront(&plist);
SListpri(plist);
printf("查找\n");
SLTNode* pos = SListFind(plist, 2);
int i = 1;
if (pos)
{
printf("第%d个节点:%->%d\n", ++i, pos, pos->next);
pos = SListFind(pos->next, 2);
}
printf("插入\n在第一个2前面插入一个20\n");
SLTNode* pos2 = SListFind(plist, 2);
if (pos) {
SListInsert(&plist, pos2, 20);
}
SListpri(plist);
return 0;
}