Created
February 26, 2013 10:41
-
-
Save hit9/5037573 to your computer and use it in GitHub Desktop.
如何翻转链表中的相邻两个元素?
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
/* | |
* Q: 如何翻转链表中的相邻两个元素? | |
* Link: http://www.foreach.cn/question/16 | |
* 比如原链表是: | |
* a->b->c->d->e->f | |
* 我们只翻转相邻两个,即1和2翻转,3和4翻转,翻转后如下: | |
* b->a->d->c->f->e | |
*/ | |
#include <stdio.h> | |
typedef struct nodeStruct { | |
int data; | |
struct nodeStruct *next; | |
} node; | |
//print list | |
void P(node *head){for(; head; printf("%d", head->data), head = head->next);} | |
void foo(node *head){ | |
// add one node before head | |
node x = {0, head}, *p=head, *m=&x, *n, *q; | |
while(p){ | |
// .. m->p->n->q .. | |
n = p->next; | |
if(n) q = n->next; | |
else break; | |
// turn to: m->n->p->q | |
m->next = n; | |
n->next = p; | |
p->next = q; | |
//update m and p for next iter | |
m = p; | |
p = q; | |
} | |
} | |
int main() | |
{ | |
node f={6, 0}, e = {5, &f}, d = {4, &e}, c = {3, &d}, b = {2, &c}, a = {1, &b}; | |
P(&a); | |
printf("\n"); | |
foo(&a); | |
P(&b); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment