【发布时间】:2018-02-18 22:38:57
【问题描述】:
在准备面试时,我目前正在复习和审查我的数据结构。我目前正在解决这个问题,我必须交换链接列表中的每 2 个节点。我的代码如下:
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
while (head != null && head.next != null){
ListNode cur = head;
ListNode prev = head.next;
head = prev;
head.next = cur;
head.next.next = prev.next;
head = prev.next;
}
return dummy.next;
}
尽管我的逻辑对我来说似乎很合理,但由于某种原因,这给了我一个无限循环。我做错了什么?
【问题讨论】:
-
你试过调试吗?
-
1) 如果 head.next.next 不存在怎么办?并且只有 head.next 存在? 2)永远不要修改函数的参数,即head。使用温度。
标签: java data-structures linked-list nodes swap