我一直在考慮的任務創建爲C.鏈表我停留在交換方法,它只是似乎亂了整個鏈表的各種方法。有人對我出錯的地方有任何建議嗎?乾杯!交換位置用C
這是我的代碼。
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
請提供更多信息:確切地說,當您對列表進行排序時會發生什麼?什麼是投入,產出和預期產出? – razlebe
交換功能和提醒的定義以外的代碼是否真的有必要? – BrainSteel
爲什麼在'swapPositionOf'的開頭多餘的強制轉換? (爲什麼首先賦值爲'pFirst'&second?) – Kninnug