Skip to content

Instantly share code, notes, and snippets.

@hit9
Created February 26, 2013 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hit9/5037573 to your computer and use it in GitHub Desktop.
Save hit9/5037573 to your computer and use it in GitHub Desktop.
如何翻转链表中的相邻两个元素?
/*
* 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