-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswapPairsLL.c
More file actions
51 lines (41 loc) · 940 Bytes
/
Copy pathswapPairsLL.c
File metadata and controls
51 lines (41 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* newNode(int x) {
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = x;
temp->next = NULL;
return temp;
}
Node* swapPairs(Node* head) {
if (!head || !head->next) return head;
Node* newHead = head->next;
Node* prev = NULL;
while (head && head->next) {
Node* nxt = head->next;
head->next = nxt->next;
nxt->next = head;
if (prev) prev->next = nxt;
prev = head;
head = head->next;
}
return newHead;
}
void printList(Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head = swapPairs(head);
printList(head);
return 0;
}