【发布时间】:2010-05-15 04:27:52
【问题描述】:
给定一个数字链表。每 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;
}
}
【问题讨论】:
-
是的,我从那里收到了问题,但已经以我的方式实施了......想知道我是否可以在这里找到更好的解决方案
-
没有人说不使用额外的存储空间
标签: algorithm linked-list