交换链表的相邻元素 [英] Swapping adjacent elements of linked list

查看:63
本文介绍了交换链表的相邻元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码,用于递归交换链表的相邻元素.交换后,我失去了指向第二个元素的指针.输入是1-> 2-> 3-> 4-> 5-> 6-> 7,我期望输出2-> 1-> 4-> 3-> 6-> 5-> 7,但我的输出是1-> 3-> 5-> 7.

The below is my code to recursive swap the adjacent elements of a linked list. I am losing the pointer to every second element after the swap. The input is 1->2->3->4->5->6->7, I expected the output 2->1->4->3->6->5->7, but my output is 1->3->5->7.

void nodelist::swap(node* head)
{

    node* temp = head->next;
    if (head->next!= nullptr)
    {
        node* temp2 = temp->next;
        temp->next = head;
        head->next = temp2;
        head = head->next; 
        temp = nullptr;
        temp2 = nullptr;
        swap(head);
    }
}

我们将不胜感激,谢谢您.

Any help would be appreciated,thanks in advance.

推荐答案

使用递归:

void nodelist::swap(node** head) {
  if (!*head || !(*head)->next) return;
  node* const sw = (*head)->next;
  (*head)->next = sw->next;
  sw->next = *head;
  *head = sw;
  swap(&(sw->next->next));
}

这篇关于交换链表的相邻元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆