单链表由数据域和指针域构成,数据域存储的这个节点的数据,指针域存储的是下一个节点的地址。
由此创建一个结构体
typedef int SLTDataType;
typedef struct SListNode
{
SLTDataType data;
struct SListNode* next;
}SLTNode;
在整个单链表的实现中,把数据的定义放到SList.h文件中,在实现每个函数写在SList.c中,同时创建一个主函数用于测试
在SList.c中写如下代码
typedef struct SLTDataType;
typedef struct SListNode{
SLTDataType data;
struct SListNode* next;
}SLTNode;
//创建一个新的节点
SLTNode* BuySLTNode(SLTDataType x){
SLTNode* NewNode=(SLTNode*)malloc(sizeof(SLTNode));
if(NewNode==NULL){
perror("malloc failed");
exit(-1);
}
NewNode->data=x;
NewNode->next=NULL;
}
//创建n个节点
SLTNode* CreateSLTNode(int n){
SLTNode* phead=NULL,*tail=NULL;
SLTNode* NewNode=BuyNode(x);
for(int i=0;i<n;i++){
if(phead==null){
tail=phead=NewNode;
}
else{
tail->next=NewNode;
tail=tail->next;
}
}
return phead;
}
//尾插数据为n的节点
void SLTPushBack(STLNode** pphead,SLTDataType x){
SLTNode* newnode=BuyNode(x);
SLTNode* tail=*pphead;
if(*pphead==NULL){
*pphead=newnode;
}
else{
while(tail->next){
tail=tail->next;
}
tail->next=newnode;
}
}
//尾删数据
void SLTPopBack(SLTNode** pphead){
assert(*pphead);
STLNode* tail=*pphead;
if((*pphead)->next==NULL){
free(*pphead);
(*pphead)->next=NULL;
}
else{
while(tail->next->next){
tail=tail->next;
}
free(tail->next);
tail->next=NULL;
}
}
//头插数据
void SLTPushFront(SLTNode** pphead,SLTDataType x){
SLTNode* newnode=BuyNode(x);
newnode->next=*pphead;
*pphead=newnode;
}
//头删数据
void SLTPopFront(SLTNode** pphead){
assert(*pphead);
SLTNode* next=(*pphead)->next;
free(*pphead);
(*pphead)->next=NULL;
*pphead=next;
}
//查找数据
SLTNode* SLTfind(SLTNode* phead,SLTDataType x){
SLTNode* cur=phead;
while(cur){
if(cur->data==x){
return cur;
}
cur=cur->next;
}
return NULL;
}
//插入一个元素,在链表pos位置之后
void SLTInsertAfter(SLTNode* pos,SLTDataType x){
assert(pos);
SLTNode* NewNode=BuySLTNode(x);
NewNode->next=pos->next;
pos->next=NewNode;
}
//插入一个元素,在链表的pos位置之前插入
void SLTInsert(SLTNode** pphead,SLTNode* pos,SLTDataType x){
assert(pos);
assert(*pphead);
SLTNode* NewNode=BuySLTNode(x);
//头插
if(*pphead=pos){
NewNode->next=*pphead;
*pphead=NewNode;
}
else{
while(pre->next!=pos){
pre=pre->next;
}
pre->next=NewNode;
NewNode->next=pos;
}
}
//删除一个元素,在pos位置之后删除
void SLTEarseAfter(SLTNode* pos)
{
assert(pos);
SLTNode* nextNode=pos->next;
pos->next=pos->next->next;
free(nextNode);
nextNode=NULL;
}
//删除一个元素,在pos位置删除
void SLTEarse(SLTNode**pphead,SLTNode* pos){
assert(pos);
assert(*pphead);
if(*pphead==pos){
SLTNode* cur=*pphead;
*phead=(*pphead)->next;
free(cur);
cur=NULL;
}
else{
SLTNode* pre=*pphead;
while(pre->next!=pos)
{
pre=pre->next;
}
pre->next=pos->next;
free(pos);
pos=NULL;
}
}