c语言,带头不循环单链表。
SList.h
#pragma once#include<stddef.h>//NULL
#include<stdlib.h>//free
#include<assert.h>//asserttypedef int SLTDataType;typedef struct SLTNode
{SLTDataType data;struct SList* pnext;
}SLTNode;SLTNode* SLTInit();void SLTPushFront(SLTNode* phead, SLTDataType x);void SLTPushBack(SLTNode* phead, SLTDataType x);
SLTDataType SLTPopBack(SLTNode* phead);SLTDataType SLTPopFront(SLTNode* phead);
SList.c
#include "SList.h"static SLTNode* BuySLTNode(SLTDataType x)
{SLTNode* pnewNode = (SLTNode*)malloc(sizeof(SLTNode));if (NULL == pnewNode){perror("malloc failed");exit(-1);}pnewNode->data = x;pnewNode->pnext = NULL;return pnewNode;
}SLTNode* SLTInit()
{return BuySLTNode(0);
}void SLTPushFront(SLTNode* phead, SLTDataType x)
{SLTNode* pnewNode = BuySLTNode(x);pnewNode->pnext = phead->pnext;phead->pnext = pnewNode;
}void SLTPushBack(SLTNode* phead, SLTDataType x)
{while (phead->pnext)phead = phead->pnext;SLTNode* pnewNode = BuySLTNode(x);phead->pnext = pnewNode;
}SLTDataType SLTPopBack(SLTNode* phead)
{assert(phead->pnext);SLTNode* pDel = phead->pnext;while (pDel->pnext){phead = phead->pnext;//找最后一个的前一个pDel = pDel->pnext;//找最后一个}SLTDataType ret = pDel->data;phead->pnext = NULL;free(pDel);return ret;
}SLTDataType SLTPopFront(SLTNode* phead)
{assert(phead->pnext);SLTNode* pDel = phead->pnext;SLTDataType ret = pDel->data;phead->pnext = pDel->pnext;free(pDel);return ret;
}
test.c
#include<stdio.h>
#include"SList.h"static void print(SLTNode* phead)
{phead = phead->pnext;while (phead){printf("%d->", phead->data);phead = phead->pnext;}printf("NULL\n");
}void test1()
{SLTDataType ret = 0;SLTNode* plist1 = SLTInit(); print(plist1);SLTPushFront(plist1, 1); print(plist1);SLTPushFront(plist1, 2); print(plist1);SLTPushFront(plist1, 3); print(plist1);SLTPushFront(plist1, 4); print(plist1);SLTPushBack(plist1, 111); print(plist1);SLTPushBack(plist1, 112); print(plist1); ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);
}int main()
{test1();return 0;
}