单向链表删除节点

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值