Skip to content

Commit

Permalink
Swap nodes in pairs
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 17, 2017
1 parent 7704a64 commit c56dc80
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 024_swap_nodes_in_pairs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test swap_nodes.c
56 changes: 56 additions & 0 deletions 024_swap_nodes_in_pairs/swap_nodes.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <stdio.h>
#include <stdlib.h>

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

static struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode dummy, *p, *prev, *next;
if (head == NULL) {
return NULL;
}
dummy.next = head;
prev = &dummy;
p = dummy.next;
next = p->next;
while (p != NULL && next != NULL) {
prev->next = next;
p->next = next->next;
next->next = p;
prev = p;
p = p->next;
if (p != NULL) {
next = p->next;
}
}
return dummy.next;
}

int main(int argc, char **argv)
{
int i;
struct ListNode *p, *prev, dummy, *list;

dummy.next = NULL;
prev = &dummy;
for (i = 1; i < argc; i++) {
p = malloc(sizeof(*p));
int n = atoi(argv[i]);
printf("%d ", n);
p->val = n;
p->next = NULL;
prev->next = p;
prev = p;
}
putchar('\n');

list = swapPairs(dummy.next);
for (p = list; p != NULL; p = p->next) {
printf("%d ", p->val);
}
putchar('\n');

return 0;
}

0 comments on commit c56dc80

Please sign in to comment.