c++ - 交换链表中的相邻节点(迭代方法)

标签 c++ linked-list

问题解释: 我必须像这样交换相邻的对:
输入:1 -> 2 -> 3 -> 4 -> 5 -> NULL
输出:2 -> 1 -> 4 -> 3 -> 5 -> NULL
此代码给出段错误。另外我想知道这个逻辑对不对?

listnode* swapPairs(listnode* head) {
    /* corner cases not included, don't bother */
    listnode *prev = head;    //points to first node
    listnode *curr = prev -> next;      //points to second
    head = curr;    //displacing head to the second element of list
    listnode *next;      //points to next of second
    while(curr != NULL || prev != NULL) {
        next = curr -> next;      
        curr -> next = prev;
        prev -> next = next;
        prev = next;
        curr = prev -> next;
    }
    return head;   

最佳答案

有几个问题,你没有检查headhead->next 是否为NULL。然后你不检查 curr = prev -> next; 是否为 NULL,如果节点数不是偶数,这是一个问题。

即便如此,该算法还是有缺陷的,第一次交换是正确的,但随后的每次交换都会失败,因为指向第一个节点的节点将被交换,没有更新。

我建议您交换节点的值,这要简单得多,因为不必修改成员 next

关于c++ - 交换链表中的相邻节点(迭代方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256660/

相关文章:

c++ - 递归链表差异

c - 当我更改字符数组时链表更改

c - 从队列中使用 dequeue 方法时抛出异常

java - 单链表中的 head.next 是如何改变的

c++ - 获取包含 Null 终止字符串的字符串的长度

c++ - 构建Qt时出现编译器错误

c++ - C++ 中的 vector 问题

c++11 - 让 result_of、decltype、std::function 和可变参数模板一起工作

c++ - std::string 的生命周期作为参数传递

c - 在C中按字母顺序插入链表