给定一个数字链表。交换每 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/