循环链表与单链表的判空:
循环链表:head->next = head
单链表:head->next = NULL
初始化:
// 初始化循环链表
void ds_init(node **pNode)
{
int item;
node *temp;
node *target;
printf("输入结点的值,输入0代表结束输入\n");
while(1)
{
scanf("%d", &item);
fflush(stdin);
if (item == 0)
{
return;
}
// 如果原先的链表是空表
if ((*pNode) == NULL)
{
*pNode = (node*) malloc(sizeof(struct CLinkList));
(*pNode)->data = item;
(*pNode)->next = *pNode;
}
else
{
for (target = (*pNode); target->next != (*pNode); target = target->next);
temp = (node*) malloc(sizeof(struct CLinkList));
if(!temp)
exit(0);
temp->data = item;
temp->next = *pNode;
target->next = temp;
}
}
}
插入操作:
// 在第i个结点前插入结点
void ds_insert(node **pNode, int i, int item)
{
node *temp;
node *target;
node *p;
int j = 1;
if (i == 1)
{
temp = (node*) malloc(sizeof(struct CLinkList));
if(!temp)
exit(0);
temp->data = item;
// 找到最后一个结点
for (target = (*pNode); target->next != (*pNode); target = target->next);
temp->next = *pNode;
target->next = temp;
*pNode = temp;
}
else
{
target = *pNode;
for (; j < i-1; j++)
{
target = target->next;
}
temp = (node*)malloc(sizeof(struct CLinkList));
if(!temp)
exit(0);
temp->data = item;
p = target->next;
target->next = temp;
temp->next = p;
}
}
删除操作:
// 删除第i个结点
void ds_delete(node **pNode, int i)
{
node *temp;
node *target;
int j = 1;
if (i == 1)
{
// 找到最后一个结点
for (target = (*pNode); target->next != (*pNode); target = target->next);
temp = *pNode;
target->next = temp->next;
free(temp);
}
else
{
target = *pNode;
for (; j < i-1; ++j)
{
target = target->next;
}
temp = target->next;
target->next = temp->next;
free(temp);
}
}
这篇博客介绍了循环链表和单链表的判空方法,并提供了初始化、插入新结点以及删除指定位置结点的C语言实现。初始化循环链表时,通过判断链表是否为空创建首结点,并形成环状。插入操作支持在任意位置插入新结点,删除操作则能移除给定位置的结点。
154

被折叠的 条评论
为什么被折叠?



