c单链表,带头结点
#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
typedef struct Node
{
Elemtype data;
struct Node *next;
} Node, *pNode;
void InitHead(pNode p)
{
p->data = 0;
p->next = NULL;
}
pNode CreatNode(Elemtype data)
{
pNode node = (pNode)malloc(sizeof(Node));
if (node)
{
node->data = data;
node->next = NULL;
return node;
}
return NULL;
}
void PrintList(pNode p)
{
int n = p->data;
p = p->next;
if (n <= 0 || !p)
{
printf("print error\n");
return;
}
for (int i = 0; i < n; i++)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
// return pos的前一个elem
pNode SearchPos(pNode p, int pos)
{
if (p->next == NULL)
{
if (pos == 0)
return p;
else
return NULL;
}
if (pos == 0 && p->next)
return p;
for (int i = 0; i < pos; i++)
{
p = p->next;
if (!p)
return NULL;
}
return p;
}
int InsertData(pNode p, int pos, Elemtype data)
{
if (p->next == NULL)
{
pNode node = CreatNode(data);
if (node)
{
p->next = node;
p->data += 1;
return 1;
}
else
{
printf("Insert Error\n");
return 0;
}
}
else
{
pNode res = SearchPos(p, pos);
if (res)
{
pNode temp = res->next;
pNode node = CreatNode(data);
if (node)
{
res->next = node;
node->next = temp;
p->data += 1;
return 1;
}
}
}
return 0;
}
int Update(pNode p, int pos, int new_data)
{
if (p->data <= 0 || p->next == NULL)
return 0;
pNode temp = SearchPos(p, pos);
if (temp)
{
temp->next->data = new_data;
return 1;
}
return 0;
}
int Delete(pNode p, int pos)
{
if (p->data <= 0 || p->next == NULL)
{
printf("delete error\n");
return 0;
}
pNode temp = SearchPos(p, pos);
if (temp)
{
pNode pp = temp->next;
temp->next = temp->next->next;
free(pp);
p->data -= 1;
return 1;
}
return 0;
}
void Clear(pNode p)
{
p->data = 0;
}
int main(void)
{
Node Head;
InitHead(&Head);
pNode ptr = &Head;
InsertData(ptr, 0, 1);
InsertData(ptr, 1, 2);
InsertData(ptr, 0, 3);
InsertData(ptr, 1, 4); // 3 4 1 2
PrintList(ptr);
Update(ptr, 3, 20); // 3 4 1 20
PrintList(ptr);
Delete(ptr, 3);
Delete(ptr, 1);
PrintList(ptr); // 3 1
Clear(ptr);
PrintList(ptr);
return 0;
}