Skip to content

Commit 26c4a54

Browse files
authored
Create 0024-swap-nodes-in-pairs.c
1 parent 40c6d6d commit 26c4a54

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Diff for: c/0024-swap-nodes-in-pairs.c

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Given a linked list, swap every two adjacent nodes and return its head.
3+
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
4+
5+
Ex. Input: head = [1,2,3,4]
6+
Output: [2,1,4,3]
7+
8+
Time : O(N)
9+
Space : O(1)
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* struct ListNode {
15+
* int val;
16+
* struct ListNode *next;
17+
* };
18+
*/
19+
struct ListNode* swapPairs(struct ListNode* head) {
20+
if (head == NULL || head->next == NULL)
21+
return head;
22+
23+
struct ListNode *new_head = head->next;
24+
struct ListNode *prev = NULL;
25+
26+
while (head != NULL && head->next != NULL) {
27+
struct ListNode *next_pair = head->next->next;
28+
struct ListNode *second = head->next;
29+
30+
if (prev != NULL)
31+
prev->next = second;
32+
33+
second->next = head;
34+
head->next = next_pair;
35+
36+
prev = head;
37+
head = next_pair;
38+
}
39+
40+
return new_head;
41+
}

0 commit comments

Comments
 (0)