#include "test.h"
SListNode* BuyNode(DataType x)
{
SListNode* node = (SListNode*)malloc(sizeof(SListNode));
node->data = x;
node->next = NULL;
return node;
}
void PrintSList(SListNode*& pHead)
{
assert(pHead);
SListNode* cur = pHead;
while (cur)
{
printf("%d ",cur->data);
cur = cur->next;
}
}
void InitSList(SListNode*& pHead)
{
pHead = NULL;
}
void DistorySList(SListNode*& pHead)
{
assert(pHead);
while (pHead)
{
SListNode* cur = pHead;
pHead = pHead->next;
free(cur);
}
pHead = NULL;
}
void PushBack(SListNode*& pHead, DataType x)
{
if (pHead == NULL)
{
pHead = BuyNode(x);
}
else
{
SListNode* cur = pHead;
while (cur->next)
{
cur = cur->next;
}
cur->next = BuyNode(x);
}
}
void PopBack(SListNode*& pHead)
{
//1.空
//2.一个节点
//3.多个节点
if (pHead == NULL)
{
printf("List is empty!\n");
return;
}
else if (pHead->next == NULL)
{
free(pHead);
pHead = NULL;
}
else
{
SListNode* cur = pHead;
SListNode* prev = NULL;
while (cur->next!=NULL)
{
prev = cur;
cur = cur->next;
}
prev = NULL;
free(cur);
}
}
void PushFront(SListNode*& pHead, DataType x)
{
if (pHead == NULL)
{
pHead = BuyNode(x);
}
else
{
SListNode* newHead = NULL;
newHead = BuyNode(x);
newHead ->next = pHead;
pHead = newHead;
}
}
void PopFront(SListNode*& pHead)
{
if (pHead == NULL)
{
printf("List is empty!\n");
return;
}
else if (pHead->next == NULL)
{
free(pHead);
pHead = NULL;
}
else
{
SListNode* cur = pHead;
pHead = pHead->next;
free(cur);
}
}
//在pos之前插入x
void Insert(SListNode*& pHead,SListNode*& pos, DataType x)
{
SListNode* cur = pHead;
SListNode* prev=NULL;
if (pHead->next == NULL)
{
PushFront(pHead, x);
}
else
{
while (cur != pos)
{
prev = cur;
cur = cur->next;
}
SListNode* newNode = BuyNode(x);
newNode->next = cur;
prev->next = newNode;
}
}
//按位置删除节点
void Erase(SListNode*& pHead, SListNode* pos)
{
assert(pos && pHead);
if (pos == pHead)
{
PopFront(pHead);
}
else
{
SListNode* cur = pHead;
SListNode* prev = NULL;
while (cur != pos)
{
prev = cur;
cur = cur->next;
}
prev->next = cur->next;
free(cur);
}
}
void Remove(SListNode*& pHead, DataType x)
{
SListNode* del=Find(pHead,x);
Erase(pHead, del);
}
SListNode* Find(SListNode*& pHead, DataType x)
{
SListNode* cur = pHead;
while (cur)
{
if (cur->data == x)
{
return cur;
break;
}
cur = cur->next;
}
if (cur == NULL)
{
return NULL;
}
}
单链表相关操作
最新推荐文章于 2017-08-10 10:18:49 发布