我怎么样在C排队功能列表? [英] How I sort list with enqueue function in c?

查看:109
本文介绍了我怎么样在C排队功能列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录:

list= C,3 -->C,5,---> A,7 --> A,5 --> G,2--> C,11 -->A,4

我outuput:

my outuput :

output= C,5  C,11 G,2 A,7 A,4 A,5 C,3

但有一些错误。我写我的code像答案,我写charcmp功能,并与charcmp STRCMP取代。它的工作原理有时corrcectly。但通常第一要素是放错了地方。我整理code喜欢回答的code

but there is some mistakes. I write my code like in answers and I write charcmp function and replace with strcmp with charcmp. It works sometime corrcectly. But usually first element is in the wrong place .My sorting code likes answer's code

推荐答案

以下code应该做的工作。这将添加到列表年龄顺序增加:

The following code should do the work. It will add to the list in increasing age order:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _node_t {
    int age;
    char *name;
    struct _node_t *nextPtr;
} node_t;

node_t *node;

void enqueue(char *name, int age)
{
    node_t *p, *prev, *n;
    /* if empty list create first element and return */
    if (node == NULL)
    {
        node = (node_t *)malloc(sizeof(node_t));
        node->nextPtr = NULL;
        node->name = (char *)malloc(strlen(name) + 1);
        strcpy(node->name, name);
        node->age = age;
        return;
    }
    p = prev = node;
    /* search last element or element with superior age value */
    while((p->nextPtr != NULL) && strcmp(p->name, name) < 0)
    {
        prev = p;
        p = p->nextPtr;
    }
    if (strcmp(p->name, name) == 0)
    {
        while((p->nextPtr != NULL) && p->age < age)
        {
            prev = p;
            p = p->nextPtr;
        }
    }
    /* create the new element and store the data */
    n = (node_t *)malloc(sizeof(node_t));
    n->name = (char *)malloc(strlen(name) + 1);
    strcpy(n->name, name);
    n->age = age;
    /* insert the new element */
    if ((strcmp(p->name, name) < 0) || (strcmp(p->name, name) == 0 && p->age < age))
    {
        n->nextPtr = p->nextPtr;
        p->nextPtr = n;
    }
    else
    {
        n->nextPtr = p;
        if (prev->nextPtr == p)
        {
            prev->nextPtr = n;
        }
        else if (node == p)
        {
            node = n;
        }
    }
}

void printNodes()
{
    node_t *p;
    p = node;
    while(p != NULL)
    {
        printf("%s, %d\n", p->name, p->age);
        p = p->nextPtr;
    }
}

int main(int argc, char **argv)
{
    node = NULL;
    enqueue("Kill", 15);
    enqueue("Bill", 2);
    enqueue("Kill", 7);
    printNodes();

    return 0;
}

所以下面的添加:

So the following adding:

enqueue("Kill", 15);
enqueue("Bill", 2);
enqueue("Kill", 7);

将其存储在由 printNodes()打印的顺序

Bill, 2
Kill, 7
Kill, 15

更新:

添加名称排序,然后年龄。

Added name sorting then age.

这篇关于我怎么样在C排队功能列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆