交换 LinkedList 的相邻节点

Val*_*ade 5 algorithm data-structures

我必须在链表中交换两个相邻的节点(不是它们的数据)。例如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;
}
Run Code Online (Sandbox Code Playgroud)

Spu*_*dun 3

看起来不错。我添加了一项正确性检查(third==NULL)并删除了一个冗余表达式。您只需浏览整个列表一次,这是您必须做的。所以我认为我们可以非常确定这是最快的方法。

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;
       second = first->next=((third==NULL || third->next==NULL) ? third : third->next);
       first=third;
       third=(second==NULL ? second : second->next);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)