Swapping adjacent elements of linked list

前端 未结 4 651
执念已碎
执念已碎 2021-01-16 09:50

The below is my code to recursive swap the adjacent elements of a linked list. I am losing the pointer to every second element after the swap. The input is 1->2->3->4->5->6-

4条回答
  •  醉酒成梦
    2021-01-16 10:41

    If head is the pointer which stores the address of firstNode (value=1), then try following function:

    void nodelist::swap(node* head){
        node* temp = head->next; //head->next is first-node which needs to switch with it's next node
        if (temp!= nullptr && temp->next!=nullptr){
            head->next=temp->next;  //move second node to first
            temp->next = head->next->next; //put second's next in first's
            head->next->next = temp; //and first will be second's next
            temp = nullptr; // swaping done
            swap(head->next->next); //do it for next couple
        }
    }
    

    http://coliru.stacked-crooked.com/a/e1cc0d02b5599da4

    OR

    http://coliru.stacked-crooked.com/a/a1e200b687825d80

    If head itself is the firstNode (value=1), then passing head by value will not work, either you need to pass it by address/reference OR do it like in following link:

    http://coliru.stacked-crooked.com/a/a1e200b687825d80

提交回复
热议问题