在C中的单链表中交换位置

use*_*328 5 c linked-list singly-linked-list

我已经被赋予了为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;
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

------Before------

Mikes Birthday
Als Soccer Match
School Concert

------After-aa-----
School Concert
Als Soccer Match    
Mikes Birthday
Run Code Online (Sandbox Code Playgroud)

输出:

------Before------

Mikes Birthday
Als Soccer Match
School Concert

------After-aa-----

Mikes Birthday
Run Code Online (Sandbox Code Playgroud)

Mr.*_*C64 1

如果你想交换列表节点的内容,那么这并不难:你只需交换两个节点中的message和字段即可。dateOfEvent

但如果你想交换这些节点的位置(正如函数名称所示),那么你必须注意pNext数据成员。
事实上,仅仅交换节点指针是不够的。您需要找到和之前
的节点位置,然后执行以下操作: firstlast

/* reminder_t* beforeFirst, reminder_t* beforeSecond */
beforeFirst->pNext = second;
beforeSecond->pNext = first;
Run Code Online (Sandbox Code Playgroud)

并交换first->pNextsecond->pNext.

此外,在这些列表实现中,通常重要的是要注意头节点和尾节点等特殊情况。