#include<stdio.h>
typedef int DataType;
typedef struct ListNode
{
DataType data;
struct ListNode* next;
}Node;
void PrintList(Node* pList)
{
while (pList)
{
printf( "%d \n",pList->data);
pList = pList->next;
}
}
void PushBack(Node** ppList, DataType x)
{
if (*ppList == NULL)
{
*ppList = (Node*)malloc(sizeof(Node));
(*ppList)->next = NULL;
(*ppList)->data = x;
}
else
{
Node*cur = *ppList;
Node*prev = NULL;
while (cur)
{
prev = cur;
cur =(cur)->next;
}
cur = (Node*)malloc(sizeof(Node));
cur->next = NULL;
cur->data = x;
prev->next = cur;
}
}
void PopBack(Node** ppList)
{
Node* cur = *ppList;
Node* prev = NULL;
if (*ppList == NULL)
{
printf("List is NULL");
return;
}
while (cur->next)
{
prev = cur;
cur = cur->next;
}
prev->next = NULL;
free(cur);
cur = NULL;
}
void PushFront(Node** ppList, DataType x)
{
if (*ppList == NULL)
{
*ppList = malloc(sizeof(Node));
(*ppList)->data = x;
(*ppList)->next = NULL;
}
else
{
Node* next = *ppList;
(*ppList)->data = x;
(*ppList)->next = next;
}
}
void PopFront(Node** ppList)
{
if (*ppList == NULL)
{
return;
}
Node* cur = *ppList;
*ppList = (*ppList)->next;
free(cur);
cur = NULL;
}
Node* Find(Node* pList, DataType x)
{
while (pList)
{
if (pList->data == x)
return pList;
else
{
pList = pList->next;
}
}
return NULL;
}
// 在pos的前面插入一个节点x
void Insert(Node** ppList, Node* pos, DataType x)
{
Node* cur = *ppList;
Node* prev = NULL;
if (*ppList==NULL||pos == NULL)
{
return;
}
if (pos == cur)//头插
{
PushFront(ppList, x);
}
else
{
while (cur)
{
if (cur == pos)
{
break;
}
else
{
prev = cur;
cur = cur->next;
}
}
if (cur == NULL)
{
return ;
}
else
{
Node*newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
prev->next = newNode;
newNode->next = cur;
}
}
}
void Erase(Node** ppList, Node* pos)
{
Node* cur = *ppList;
Node* prev = NULL;
Node* next = NULL;
if (*ppList == NULL || pos == NULL)
{
return;
}
else if (pos == *ppList)
{
PopFront(ppList);
}
else
{
while (cur)
{
if (cur == pos)
{
break;
}
else
{
prev = cur;
cur = cur->next;
}
}
if (cur == NULL)
{
return;
}
else
{
next = cur->next;
prev->next = next;
}
}
}
void FunTest()
{
Node* pHead = NULL;
PushBack(&pHead, 5);
PushBack(&pHead, 1);
PushBack(&pHead, 2);
PushBack(&pHead, 3);
Node*tmp = Find(pHead, 6);
Erase(&pHead, tmp);
//Insert(&pHead, tmp, 6);
//PrintList(pHead);
//Node* find = Find(pHead, 2);
//Node* find2 = Find(pHead, 6);
//PopBack(&pHead);
//PopBack(&pHead);
//PopFront(&pHead);
//PopFront(&pHead);
}
int main()
{
FunTest();
return 0;
}
C语言实现单链表
最新推荐文章于 2023-08-02 09:18:05 发布