【发布时间】:2013-11-29 03:37:53
【问题描述】:
我被分配在 C 语言中为链表创建各种方法。我卡在 swap 方法上,它似乎只是弄乱了整个链表。有人对我哪里出错有任何建议吗?干杯!
这是我的代码。
int main(int argc, char* argv[])
{
// A list of pointers to Reminders
const int MAX_ENTRIES = 10;
int numOfEntries = 0 ;
reminder_t* pFirst = (reminder_t*) malloc ( sizeof(reminder_t));
reminder_t* pSecond = (reminder_t*) malloc ( sizeof(reminder_t));
reminder_t* pThird = (reminder_t*) malloc ( sizeof(reminder_t));
reminder_t* pStart = NULL;
if (pFirst != NULL)
{
strcpy( pFirst->message, "Mikes Birthday");
pFirst->dateOfEvent.day= 1;
pFirst->dateOfEvent.month= 1;
pFirst->dateOfEvent.year= 2013;
pFirst->pNext = NULL;
}
if (pSecond != NULL)
{
strcpy( pSecond->message, "Als Soccer Match");
pSecond->dateOfEvent.day= 2;
pSecond->dateOfEvent.month= 2;
pSecond->dateOfEvent.year= 2013;
pSecond->pNext = NULL;
}
if ( pThird != NULL)
{
strcpy( pThird->message, "School Concert");
pThird->dateOfEvent.day= 3;
pThird->dateOfEvent.month= 3;
pThird->dateOfEvent.year= 2013;
pThird->pNext = NULL;
}
pFirst->pNext = pSecond;
pSecond->pNext = pThird;
pThird->pNext = NULL;
pStart = pFirst;
printf("\n------Before------\n");
listEntries(pStart);
swapPositonOf(pFirst,pThird);
printf("\n------After-aa-----\n");
listEntries(pStart);
getchar();
return 0;
}
void listEntries(reminder_t * pList)
{
printf("\n");
while (pList != NULL)
{
printf("%s\n", pList->message);
pList = pList->pNext;
}
}
void swapPositonOf(reminder_t* first , reminder_t* second)
{
reminder_t* pFirst = (reminder_t*) first;
reminder_t* pSecond = (reminder_t*) second;
reminder_t* temp = second->pNext;
pSecond->pNext = pFirst->pNext;
pFirst->pNext = temp;
temp = pSecond;
pSecond = pFirst;
pFirst = temp;
}
预期输出:
------Before------
Mikes Birthday
Als Soccer Match
School Concert
------After-aa-----
School Concert
Als Soccer Match
Mikes Birthday
输出:
------Before------
Mikes Birthday
Als Soccer Match
School Concert
------After-aa-----
Mikes Birthday
【问题讨论】:
-
请提供更多信息:当您对列表进行排序时会发生什么?输入、输出和预期输出是什么?
-
除了swap函数和提醒定义之外的代码真的有必要吗?
-
为什么
swapPositionOf开头有多余的演员表? (为什么将first分配给pFirst和第二个?)
标签: c linked-list singly-linked-list