【问题标题】:sort nested struct single linked and double排序嵌套结构单链接和双
【发布时间】:2014-03-05 16:35:48
【问题描述】:

我已经嵌套为:

typedef struct a{
    const char *        LongName;
    const char *        ShortName;
    int                 a;
    struct a    *       next;
}Level5;

typedef struct a1{
    const char *        LongName;
    const char *        ShortName;
    int                 frequency5;
    int                 id;
    Level5  *           linked;
    struct a1*          next_a1;
}Level4;

typedef struct a2{
    const char      *   Name;
    int                 frequency4;
    Level4      *       linked;
    int                 id;
    struct a2   *       next;
}Level3;

typedef struct a3{
    const char *        LongName;
    const char *        ShortName;
    int                 frequency3
    int                 id;
    Level3      *       linked;
}Level2;

typedef struct a4{
    const char *        LongName;
    const char *        ShortName;
    _Bool           top;
    int             id;
    int             frequency2;
    Level2      *   lined;
}Level1;


typedef struct cat{
    int         id;
const char  *   CatName;
Level1      *   linked;
}CAT;

CAT     total[256];

现在我想将链接的嵌套结构结构排序如下:

 1. Level 5 -> LongName

 2. Level 4 -> ShortName

 3. Level 3 -> Name

 4. Level 2 -> Frequency3

               Level 1
                   |
                   | Level 2
     ====================================================
     | Level3         |Level3         |level 3
 =============       
 |     next       next   
level4 ->     lev4 ->   lev4
 |              |
 |                   =====================================
===============================       |    
|       next        next           Level5 ->  level5  ->  level5
Level5  ->    Level5  ->  level5   

【问题讨论】:

  • 需要澄清一下:所有项目都是先按级别排序,然后按专业排序吗?
  • 是否所有 5 级项目都按 LongName 排序,即使它们共享公共字段?
  • @ThomasMatthews 第一个问题的答案是肯定的,这就是我要找的。 LongName 在每个结构中都不同。对于安装 level5 abc 然后 level4 def level3 ghi level2 jkl level1 xzy。名称可能相同,但每个结构中的值不同

标签: c++ c xcode visual-c++ gcc


【解决方案1】:

看起来你有以下数据结构:

Level5 node --> Level5 node --> Level5 node  
  |  
  v  
Level4 node --> Level4 node --> Level4 node  
  |  
  v  
Level3 node --> level3 node --> Level3 node  
  |  
  v  
Level2 node --> level2 node --> Level2 node  

如果是这种情况,你的数据结构可以简化:

struct Node
{
};

struct Node_Row
{
   unsigned int level;
   std::list<Node> nodes_in_row;
};

struct data_structure
{
   std::list<Node_Row> levels;
};

您应该有一个对行进行排序的比较器函数和另一个对级别进行排序的比较器函数。

此外,由于您将问题标记为 C++,因此您应该省去一些麻烦,并使用 std::string 而不是 char *std::string 为您管理动态内存分配和释放,而char * 您管理内存分配和释放。

【讨论】:

  • 我做了一些 ascii 艺术作品来展示结构以便更好地理解
猜你喜欢
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多