簡體   English   中英

無法交換鏈表中偶數個元素

[英]Unable to swap even number of elements in linked-list

我正在編寫代碼以成對交換鏈表中的元素,我的代碼在元素數為奇數的情況下可以正常工作,但在偶數個數的情況下不起作用
輸入-1-> 2-> 3-> 4-> 5-> 6-> 7
輸出2-> 1-> 4-> 3-> 6-> 5-> 7

 void sort()
 {
     node *ptr=head;
     node *ptr1=head;
     int temp;
     while(ptr->next!=NULL)
     {
         temp=(ptr->next)->info;
         (ptr->next)->info=ptr->info;
         ptr->info=temp;

         //This statement is not working with even number of elements as
         //when it reaches last element it is going beyond the list and 
         //I am unable to rectify how to rectify this problem
         ptr=(ptr->next)->next;
     }
 }

我認為while(ptr->next!=NULL)應該更改為while (ptr!=NULL && ptr->next!=NULL)

您無需檢查當前節點是否等於NULL。 當該語句之后的節點數為偶數時

ptr=(ptr->next)->next;

ptr可以等於NULL,您無需檢查。

該函數可以通過以下方式編寫

void adjacent_swap()
{
    for ( node *p = head; p!= NULL && p->next != NULL; p = p->next )
    {
        int tmp = p->info;
        p->info = p->next->info;
        p = p->next;
        p->info = tmp;
    }
}

重用您的代碼只需對此進行調整:

while(ptr->next!=NULL && ptr->next->next!=null )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM