algorithm - 给定一个数字链表。交换每 2 个相邻链接

标签 algorithm linked-list

给定一个数字链表。交换每 2 个相邻链接。例如,如果给你的链表是:

a->b->c->d->e->f 

预期输出:

b->a->d->c->f->e

必须交换每 2 个备用链接。

我在这里写了一个解决方案。你能建议我一些其他的解决方案吗?你能评论我的解决方案并帮助我更好地编写它吗?

void SwapAdjacentNodes (Node head)
{
    if (head == null) return; 

    if (head.next == null) return; 
    Node curr = head;
    Node next = curr.Next;
    Node temp = next.Next;

    while (true)
    {
        temp = next.Next;
        next.Next = curr;
        curr.Next = temp;

        if  (curr.Next != null)
            curr = curr.Next;
        else
            break;
        if (curr.Next.Next!=null)
            next = curr.Next.Next;
        else
            break;
    }   
}

最佳答案

看看这个 C++ 解决方案:

public void exchangeAdjElements(){
    LLMain backup=current.next;
    LLMain temp = current.next;
    LLMain previous=current;
    while(current!=null && current.next!=null){
        previous.next=current.next;
        current.next=temp.next;
        temp.next=current;
        if(current.next!=null){
            previous=current;
            current=current.next;
            temp=current.next;
        }
    }
    current=backup;
}

这里current是头节点。

关于algorithm - 给定一个数字链表。交换每 2 个相邻链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838924/

相关文章:

algorithm - 为自动索具找到重量绘画公式的因素

algorithm - 障碍物矩阵中的最小路径 SUM 计算?

algorithm - 如何计算第 n 个排列(或告诉给定排列的字典顺序)?

javascript - 链表 : or how to store a live qued-list properly

algorithm - 为什么说NP完全问题就是NP呢?

python - 在 python 中计算列表中的字符串然后过滤和匹配

c - 从 C 函数返回链表结构

java - 什么是在任何位置追加、前置和检索元素的 O(1) 复杂度的数据结构?

java - LinkedList temp.next 和 temp?

c - 这段代码不断出现段错误