c++ - 成对交换节点而不交换 LinkedList 中的数据

标签 c++ data-structures linked-list

我一直在尝试对链表元素进行成对交换。我不是通过数据交换元素,而是通过交换链接来交换它们:

输入 1:1->2->3->4->5 输出 1:2->1->4->3->5

输入 2:1->2->3->4->5->6 输出 2:2->1->4->3->6->5

#include <iostream>
using namespace std;

struct node{
  int data;
  struct node *next;
};

struct node* func(struct node *f, struct node *s){
    if(s==NULL){
        return f;
    }

    struct node *rest1;
    rest1 = s->next;

    s->next = f;
    if(rest1){
        f->next = func(rest1,rest1->next);
    }

    return s;
}

void show(struct node *head){
    while(head!=NULL){
        cout<<" "<<head->data;
        head = head->next;
    }
}

int main() {
    //code
    struct node *head  =(struct node*)malloc(sizeof(struct node));
    head->data=1;
    head->next = (struct node*)malloc(sizeof(struct node));

    head->next->data = 2;
    head->next->next = (struct node*)malloc(sizeof(struct node));

    head->next->next->data = 3;
    head->next->next->next = (struct node*)malloc(sizeof(struct node));

    head->next->next->next->data = 4;
    //head->next->next->next->next=(struct node*)malloc(sizeof(struct node));
    //head->next->next->next->next->data=5;

    head = func(head,head->next);
    show(head);
    return 0;
}

此代码适用于奇数长度列表,但不适用于偶数长度。 我认为问题出在:

if(s==NULL){
    return f;
}

我用来制作上一个 f->next=NULL 的语句(在偶数长度的情况下)。

最佳答案

既然你把它标记为 C++,我推荐 STL 的 <list> .你可以用它来完成你想要的 splice允许您操作列表的方法。一种可能的实现类似于:

void alternate(list<int>& l)
{
    if (l.empty())
        return;
    auto from_itr = cbegin(l);
    auto to_itr = from_itr;
    for (; ++to_itr != cend(l) && ++to_itr != cend(l);) {
        l.splice(to_itr, l, from_itr);
        ++from_itr;
    }
}

注意: from_itr在循环中只递增一次,因为它已在列表中移动到下一个感兴趣的节点之前。

关于c++ - 成对交换节点而不交换 LinkedList 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147569/

相关文章:

c++ - 为什么在 Main 中工作正常的代码在函数内工作不正确? (C++)

c++ - 减小控制台尺寸

algorithm - 用于快速搜索由给定字母组成的单词的数据结构

algorithm - 为什么每次插入左倾红黑树后都需要将根着色为黑色?

java - 使用 radix-26 将名称转换为 key

c++ - 返回类内的私有(private)类

c - 我陷入链表的无限循环

c++ - NSArray 如何取得 C++ 对象的所有权

c++ - 模板多重继承歧义符号错误

C++ 模板 - 链表