Swapping adjacent nodes in a Linked List (Iterative Approach)

时间:2016-08-31 18:32:22

标签: c++ linked-list

Question explanation: I have to swap adjacent pairs like this:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: 2 -> 1 -> 4 -> 3 -> 5 -> NULL
This code is giving segmentation fault. Also, I wanna know whether this logic is correct or not?

listnode* swapPairs(listnode* head) {
    /* corner cases not included, don't bother */
    listnode *prev = head;    //points to first node
    listnode *curr = prev -> next;      //points to second
    head = curr;    //displacing head to the second element of list
    listnode *next;      //points to next of second
    while(curr != NULL || prev != NULL) {
        next = curr -> next;      
        curr -> next = prev;
        prev -> next = next;
        prev = next;
        curr = prev -> next;
    }
    return head;   

3 个答案:

答案 0 :(得分:1)

There are several problems, you don't check if head or head->next are NULL. Then you don't check if curr = prev -> next; is NULL, which is a problem if the number of nodes is not even.

Even so, the algorithm is flawed, the first exchange is correct, but every subsequent will fail because the node that is pointing to the first node, of the two that will be exchanged, is not updated.

I suggest you swap the values of the nodes, which is much simpler, as the members next won't have to be modified.

答案 1 :(得分:0)

首先关闭所有不需要更改链接只需将该节点的值与下一个节点交换。因为根据您的问题,您只需要交换值而不是节点,所以我不认为改变链接是个好主意,所以我建议你只需交换节点的值,然后就可以了。

答案 2 :(得分:0)

如果要求禁止只交换相邻的(这更容易做,因为它不需要任何破坏或节点之间新的连接形成),并且相反,希望交换实际的相邻节点,你需要记下最后交换的相邻节点 tail 所有时间

listnode* swapPairs(listnode* head) {
    listnode *prev = head;    
    listnode *curr;
    listnode *next = null, *tail = null;      
    while(prev != null && prev->next != null) {
        curr = prev->next;
        next = curr->next;      
        curr->next = prev;
        if(tail != null) tail->next = curr;
        else head = curr; //First two nodes are swapped. First node (previously second node) will be new head
        tail = prev;      //Tail of lastly swapped nodes i.e. previously first one of them 
        prev = next;      //Swapping done between curr and pre, now move to next node 
    }
    if(tail != null) {
       tail->next = next; 
    }
    return head;  
}