我需要在一个链表中交换两个相邻的节点(不是它们的数据)。
例如:
1) 输入a->b->c->d->e->f,输出:b->a->d->c->f->e
2) 输入a->b->c->d->e,输出:b->a->d->c->e
我已经编写了以下代码,还有更有效的方法(也许使用两个临时指针)或简单的逻辑吗?
node* swap(node* head) {
node *first = head;
node *second,*third,*result;
if(head == NULL || head->next == NULL) {
return head;
}
result = second = first->next;
third = second->next;
while(second != NULL) {
second->next=first;
first->next=(third->next==NULL ? third : third->next);
first=third;
second=(third->next==NULL ? third : third->next);
third=(second==NULL ? second : second->next);
}
return result;
}