我有以下 *addEngine 函数,它将元素添加到我的链表中,我想按年份升序排序。我不能更改函数参数。
它不像我想象的那样工作。为什么
a = AddEngine ( a, createEngine ( "TDI 1.9", 2015) );
在主列表中列出时不包括在内?
typedef struct TEngine
{
struct TEngine *m_Next;
int m_Year;
char m_Type [ TYPE_MAX ];
} TENGINE;
typedef struct TArchive
{
struct TArchive *m_Next;
TENGINE *m_Engines;
} TARCHIVE;
TARCHIVE *addEngine ( TARCHIVE *list, TENGINE *engine)
{
TARCHIVE *res = (TARCHIVE*) malloc(sizeof(*res));
if ( list == NULL )
{
res -> m_Next = NULL;
return res;
}
int currentYear = list -> m_Engnes -> m_Year;
if ( currentYear > engine -> m_Year )
{
TARCHIVE *prev = list;
TARCHIVE *current = list -> m_Next;
while ( current != NULL )
{
if ( currentYear >= engine -> m_Year )
{
res -> m_Next = prev -> m_Next;
prev -> m_Next = res;
return list;
}
prev = current;
current = current -> m_Next;
}
prev -> m_Next = res;
res -> m_Next = NULL;
}
return 0;
}
int main ( void )
{
TARCHIVE *a, *b;
b = a = NULL;
a = AddEngine ( a, createEngine ( "TDI 1.9", 2015) );
a = AddEngine ( a, createEngine ( "TDI 1.8", 3001 ) );
a = AddEngine ( a, createEngine ( "TSI 1.2", 1999 ) );
a = AddEngine ( a, createEngine ( "TDI 2.0", 2108 ) );
a = AddEngine ( a, createEngine ( "TDI 1.9", 2005) );
b = a = AddEngine ( a, createEngine ( "TDI 1.8", 1010 ) );
a = AddEngine ( a, createEngine ( "TDI 1.9", 2025) );
a = AddEngine ( a, createEngine ( "TDI 1.8", 2038 ) );
while ( b )
{
printf ("%s", b -> m_Engines -> m_Type);
b = b -> m_Next;``
}
这不仅仅是 2015 年。它适用于您添加的所有内容。因为您确实添加了列表结构,但永远不要将引擎结构放在列表结构中!
似乎当第一项不起作用时,您没有检查下一项是否有效。
您也在打印b
但在开始打印之前忘记b = a;
。
因此,首先,您应该执行以下操作:
if ( list == NULL )
{
res -> m_Next = NULL;
res -> m_Engines = engine; // add this line
return res;
}
然后在将项目插入/添加到列表中的位置执行此操作。
你能解释一下为什么TARCHIVE
和TENGINE
都有m_Next
吗?哪一个是你的清单?
我还注意到,当if ( currentYear > engine -> m_Year )
失败时,你什么都不做。因此,如果list -> m_Engnes -> m_Year
(第一个列表元素(大于或相等,则忽略引擎。你应该把它放在前面。
请注意m_Engnes
中的错别字;这应该是m_Engines
。你的编译器没有警告你吗?请打开编译器的警告。
谢谢你的回答。我还应该修改什么?因为问题仍然存在,但我想我错过了一些东西。
TARCHIVE *AddEngine ( TARCHIVE *list, TENGINE *engine )
{
TARCHIVE * res = ( TARCHIVE * ) malloc ( sizeof ( *res ) );
if ( list == NULL )
{
res -> m_Next = NULL;
res -> m_Engines = engine;
return res;
}
int currentYear = list->m_Engines->m_Year;
// The inserted element is smaller than the first
if ( currentYear > engine->m_Year )
{
res -> m_Next = list;
res -> m_Engines = engine;
return res;
}
TARCHIVE *prev = list;
TARCHIVE *current = list -> m_Next;
while ( current != NULL )
{
currentYear = current->m_Engines->m_Year;
if ( currentYear >= engine->m_Year )
{
res -> m_Next = prev -> m_Next;
res -> m_Engines = engine;
prev -> m_Next = res;
return list;
}
prev = current;
current = current -> m_Next;
}
prev -> m_Next = res;
res -> m_Engines = engine;
res -> m_Next = NULL;
return res;
}
return 0;
}