函数:
#include"SLl.h"
#include<stdlib.h>
#include<assert.h>
void SLTPrint(SLTNode* phead)
{
assert(phead);
SLTNode*p=phead;
while(p)
(
printf("%d->",p->data);
p=p->next;
)
printf("NULL\n");
}
//头部插入删除/尾部插入删除
void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
assert(phead);
//assert(*phead);
SLTNode*NewSLT=(SLTNode*)malloc(sizeof(SLTNode));
NewSLT->data=x;
NewSLT->next=0;
if(*phead==NULL)
{
*phead=NewSLT;
return;
}
SLTNode*p=*pphead;
while(!p->next)
{
p=p->next;
}
p->next=NewSLT;
}
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
assert(phead);
//assert(*phead);
SLTNode*newNode=(SLTNode*)malloc(sizeof(SLTNode));
assert(newNode);
newNode->data=x;
newNode->next=0;
if(*phead==NULL)
{
*phead=newNode;
return;
}
newNode->next=*pheadl;
*phead=newNode;
}
void SLTPopBack(SLTNode** pphead)
{
assert(pphead);
assert(*pphead);
if((*pphead)->next==0)
{
free(*pphead);
*pphead=0;
return;
}
//前后指针找到尾部之前的位置,且记录尾部与之前
#if 0
SLTNode*prev,*ptail;
prev=ptail=*pphead;
while(ptail->next)
{
ptail=ptail->next;
prev=prev->next;
}
prev->next=0;
free(ptail);
#endif
//一般解法
#if 1
SLTNode*p=*pphead;
while(!p->next->next)
{
p=p->next;
}
free(p->next);
p->next=0;
#endif
}
void SLTPopFront(SLTNode** pphead)
{
assert(pphead);
assert(*pphead);
SLTNode*p=*pphead;
*pphead=p->next;
free(p);
}
//查找
SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
assert(phead);
for(SLTNode*p=phead;p;p=p->next)
{
if(p->data==x)
return p;
}
return 0;
}
//在指定位置之前插入数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
assert(pphead);
assert(*pphead);
assert(pos);
SLTNode*p=*pphead;
SLTNode*newNode=(SLTNode*)malloc(sizeof(SLTNode));
newNode->data=x;
newNode->next=0;
if(p==pos)
{
newNode->next=*pphead;
*pphead=newNode;
return;
}
while(p!=0&&p->next!=pos)
{
p=p->next;
}
if(p==NULL)
{
perror(insertpos);
exit(1);
}
p->next=newNode;
newNode->next=pos;
}
//删除pos节点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
assert(pphead);
assert(*pphead);
assert(pos);
//
if(*pphead==pos)
{
free(*pphead);
*pphead=0;
return;
}
SLTNode*p=*pphead;
while(p&&p->next!=pos)
{
p=p->next;
}
p->next=p->next->next;
free(pos);
}
//在指定位置之后插入数据
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
asssert(pos);
SLTNode*newNode=(SLTNode*)malloc(sizeof(SLTNode));
if(!newNode)
{
perror("malloc");
exit(1);
}
newNode->data=x;
newNode->next=pos->next;
pos->next=newNode;
}
//删除pos之后的节点
void SLTEraseAfter(SLTNode* pos);
{
assert(pos);
SLTNode*p=pos->next;
pos->next=pos->next->next;
free(p);
}
//销毁链表
void SListDesTroy(SLTNode** pphead)
{
assert(pphead);
SLTNode*p=*pphead;
SLTNode*j=p;
while(p)
{
p=p->next;
free(j);
j=p;
}
*pphead=NULL;
}