【发布时间】:2017-10-12 03:27:24
【问题描述】:
我正在编写一个程序来创建列表、打印它并从列表中删除(3 个函数)。
Print 和 pushBack 都很好,它们工作得很好,但我不知道如何在 removeFromList() 函数中从列表中取出一个数字。
不要注意名称(如客户端、套接字),这是为了让我的客户端-服务器应用程序保存活动套接字(这就是为什么我需要在客户端断开连接时将它们从列表中删除)。
这里我有 2 个结构:listElement 和 clientList(其中包含指向 listElement 的头元素的指针)
struct listElement
{
SOCKET socket;
struct listElement* next;
};
struct clientList
{
listElement * head;
};
我的 pushBack 函数:
int pushBackСlient(struct clientList* list, int socket)
{
struct listElement* newClient = (struct listElement*)malloc(sizeof(struct listElement));
struct listElement* currentElement = list->head;
newClient->socket = socket;
newClient->next = 0;
do
{
// IT'S PUSHBACK
if (list->head == 0)
{
list->head = newClient;
break;
}
while (currentElement->next != 0)
{
currentElement = currentElement->next;
}
currentElement->next = newClient;
} while (false);
return 0;
}
我的打印:
void print(struct clientList* list)
{
struct listElement* currentElement = list->head;
while (currentElement != 0)
{
printf("%d\n", currentElement->socket);
currentElement = currentElement->next;
}
}
还有我遇到问题的功能(我制作了调试消息以查看是否正确添加了“套接字”)。我想我不需要前 3 行,但不确定。
更新13/05/2017
void removeFromList(struct clientList* list, int socket)
{
struct listElement* currentElement = list->head;
do
{
if (list->head == 0)
{
return;
}
while (currentElement != 0 && currentElement->next != 0)
{
if (currentElement->socket == socket)
{
printf("currentElement == %d\n", currentElement);
currentElement = currentElement->next;
printf("currentElement == %d\n", currentElement);
free(currentElement);
//break; // if I only want to remove the first socket?
}
currentElement = currentElement->next;
}
} while (false);
}
谢谢。
【问题讨论】:
-
您的第一个也是最重要的错误是认为这是 C!
-
这是课堂(学习)练习吗?如果不只是使用
std::list。 -
@Olaf 我不明白你为什么这么说。我也在使用 stdio.h、stdlib.h 和 winsock2.h 库
-
@RichardCritten 这是一个测试任务,但我在干净的 C 语言项目中需要它。
-
@George Z。在 C 和 C++ 之间做出选择。如果它是 C++ 程序,则使用运算符 new 而不是 malloc。如果是 C 程序,则使用 free 而不是 delete。
标签: c list pointers singly-linked-list