Swap Nodes in Pairs – LeetCode #24 (Medium) in C

Home   »   Swap Nodes in Pairs – LeetCode #24 (Medium) in C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
  if (head == NULL) {
    return NULL;
  }
  struct ListNode *first;
  int aux;
  first = head;
  while (first != NULL) {
    if (first->next != NULL) {
      /* found another pair */
      /* aux = second */
      aux = first->next->val;
      /* second = first */
      first->next->val = first->val;
      /* first = aux */
      first->val = aux;
    } else {
      /* no more pair to swap */
      break;
    }
    /* advance pointer two steps */
    first = first->next->next;
  }
  return head;
}

Leave a Reply

Your email address will not be published. Required fields are marked *