struct st_node
{
int fd;
struct st_node *next;
};
st_node *head = NULL, *tail = NULL;
void create_list()
{
st_node *node;
int i = 0;
while (i < 10)
{
node = (st_node *)malloc(sizeof(st_node));
node->fd = i;
node->next = NULL;
if (head == NULL)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
i++;
}
}
void del_node(int fd)
{
struct st_node *pre = NULL, *cur = NULL;
if (head == NULL)
return;
if (head == tail)
{// 只有一个节点
if (head->fd == fd)
{
cur = head;
head = tail = NULL;
free(cur);
}
else
{
printf("error.\n");
}
}
else
{// 有两个以上节点
if (head->fd == fd)
{// 删除头节点
cur = head;
head = head->next;
free(cur);
}
else
{// 删除非头节点
pre = NULL;
cur = head;
while (cur != NULL)
{
if (cur->fd == fd)
{
pre->next = cur->next;
if (cur == tail)// 如果是尾节点
tail = pre;
free(cur);
break;
}
pre = cur;
cur = cur->next;
}
}
}
}
void prnt_list()
{
struct st_node *node = head;
while (node != NULL)
{
printf("%d\n", node->fd);
node = node->next;
}
if (head != NULL)
{
printf("head: %d\n", head->fd);
}
if (tail != NULL)
{
printf("tail: %d\n", tail->fd);
}
}
int main(int argc, char *argv[])
{
char input[8];
create_list();
prnt_list();
printf("please input:");
memset(input, 0, sizeof(input));
while (gets(input))
{
if (strcmp(input, "exit") == 0)
break;
int del = atoi(input);
del_node(del);
prnt_list();
memset(input, 0, sizeof(input));
printf("please input:");
}
return 0;
}
单向链表删除节点
最新推荐文章于 2023-10-27 11:12:30 发布