链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
An interview question form people search, What's the fuck! Long time no use C, almost forget them all.......
Tried to implement this algorithom using C, maybe some bugs exist.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node{
char val;
struct node* pNext;
}Node;
Node* CreateList(int n);
void Traverslist(Node* pHead);
Node* TransNeighbor(Node* pHead);
int main(){
Node* pHead = CreateList(7);
printf("before tranform\n");
Traverslist(pHead);
TransNeighbor(pHead);
printf("\nafter tranform\n");
Traverslist(pHead);
getchar();
}
Node* CreateList(int n){
Node* pHead = (Node*)malloc(sizeof(Node));
Node* pTail = pHead;
pTail->pNext=NULL;
int i;
for(i=0; i < n; i++){
Node* pNew = (Node*)malloc(sizeof(Node));
pNew->val = 'a'+i;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void Traverslist(Node* pHead){
Node* p = pHead->pNext;
int isFirst = 0;
while(p!= NULL){
if(isFirst==0){
printf("%c",p->val);
isFirst=1;
}else{
printf("->%c",p->val);
}
p = p->pNext;
}
return;
}
Node* TransNeighbor(Node* pHead){
Node* p = pHead->pNext;
while(p->pNext!=NULL && p->pNext->pNext!=NULL){
char value = p->val;
p->val=p->pNext->val;
p->pNext->val=value;
p=p->pNext->pNext;
}
return pHead;
}