/*
不带空头结点的单链表
without dummy head node
*/
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
struct Node
{
ElemType data;
struct Node *next;
};
// 为了隐藏更多细节,同时创建更多的API
void InitNode(struct Node **node)
{
*node = NULL;
}
struct Node *CreatNode(int data)
{
struct Node *node;
node = (struct Node *)malloc(sizeof(struct Node));
if (node != NULL)
{
node->data = data;
node->next = NULL;
return node;
}
else
return NULL;
}
void PrintList(struct Node *node)
{
struct Node *ptr = node;
while (ptr)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
putchar('\n');
}
int Insertdata(struct Node **node, int pos, int data)
{
int cnt = 0;
if (*node == NULL) // 此时还没有元素,不管位置参数,直接作为头
{
*node = CreatNode(data);
return 1;
}
else
{
struct Node *temp = NULL;
struct Node *new = NULL;
if (pos == 0) // 插在第一位
{
new = CreatNode(data);
if (new)
{
new->next = *node;
*node = new;
return 1;
}
else
return 0;
}
else
{
temp = *node;
int cnt = 0;
new = CreatNode(data);
for (int i = 0; i < pos; i++)
{
if (!temp->next) // 到最后了还没找到
{
if (new)
{
temp->next = CreatNode(data);
return 1;
}
else
return 0;
}
else
{
if (i == pos - 1)
{
new->next = temp->next;
temp->next = new;
return 1;
}
temp = temp->next;
}
}
}
}
}
struct Node *Search_By_Index(struct Node **node, int index)
{
struct Node *ptr = *node;
for (int i = index - 1; i > 0; i--)
{
if (!ptr)
return NULL;
ptr = ptr->next;
}
return ptr;
}
int DelItem(struct Node **node, int index)
{
struct Node *ptr = *node;
if (Search_By_Index(node, index - 1))
{
if (index == 0)
{
*node = ptr->next;
free(ptr);
}
else
{
for (int i = 0; i < index - 2; i++)
ptr = ptr->next;
if (ptr->next->next)
{
ptr->next = ptr->next->next;
// free(ptr->next);
return 1;
}
else
{
ptr->next = NULL;
return 1;
}
}
return 1;
}
else
{
printf("Delete Error!\n");
return 0;
}
}
int UpdateData(struct Node **node, int old_pos, int data)
{
struct Node *ptr = Search_By_Index(node, old_pos);
if (!ptr)
return 0;
else
{
ptr->data = data;
return 1;
}
}
int main()
{
struct Node *phead;
InitNode(&phead);
Insertdata(&phead, 0, 2);
Insertdata(&phead, 0, 1);
Insertdata(&phead, 2, 3);
Insertdata(&phead, 4, 4);
PrintList(phead);
DelItem(&phead, 2);
PrintList(phead);
UpdateData(&phead, 0, 9);
PrintList(phead);
return 0;
}