24. Swap Nodes in Pairs

C++ | 100% Success | Easy Explaination | Linked-List


 /**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode() : val(0), next(nullptr) {}

 *     ListNode(int x) : val(x), next(nullptr) {}

 *     ListNode(int x, ListNode *next) : val(x), next(next) {}

 * };

 */

class Solution {

public:

    ListNode* swapPairs(ListNode* h) {

        ListNode*head = h;      

        int x=0,d;

        while(head!=NULL){

            if(x%2==0 && head->next){

                d = head->val;

                head->val = head->next->val;

                head->next->val = d;

            }

            x++;

            head  = head->next;

        }

        return h;

    }

};

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones