结构体定义
struct result
{
char ubuf[32];
char nbuf[32];
int port; /*按照port的大小排序*/
struct result* next;
};
创建节点
struct result* createNode(char* ubuf, char* nbuf, int port)
{
struct result* newNode = (struct result*)malloc(sizeof(struct result));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
strcpy(newNode->ubuf, ubuf);
strcpy(newNode->nbuf, nbuf);
newNode->port = port;
newNode->next = NULL;
return newNode;
}
添加进链表
void insertNode(struct result** head, char* ubuf, char* nbuf, int port)
{
struct result* newNode = createNode(ubuf, nbuf, port);
if (*head == NULL || port < (*head)->port)
{
// 当链表为空或新节点的 port 值小于首节点的 port值,用“头插法”
newNode->next = *head;
*head = newNode;
}
else
{
// 新节点的 port 值大于首节点的 port值,用“尾插法”
struct result* current = *head;
while (current->next != NULL && port > current->next->port)
{
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}