forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
7704a64
commit c56dc80
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test swap_nodes.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |