aboutsummaryrefslogtreecommitdiff
path: root/swap_nodes_pairs.c
blob: 45c5be5299a31b1956ba5242886022147a443983 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 24. Swap Nodes in Pairs

/*
 * given a linked list, swap every two adjacent nodes and return
 * its head. problem must be solved without modifying values
 * in the list's nodes (ie only nodes themselves may be changed)
 */

struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode *swapPairs(struct ListNode *head) {
  if (!head || !head->next)
    return head;
  struct ListNode *tmp = head->next;
  head->next = swapPairs(head->next->next);
  tmp->next = head;
  return tmp;
}