【发布时间】:2019-06-13 21:34:48
【问题描述】:
我正在尝试实现代码以交换链表中的两个相邻对,但在理解我的错误所在时遇到了一些麻烦。
这是一个用Java编程语言实现的leetcode问题,我首先尝试了一个迭代解决方案,我分配了第一个初始节点和第三个初始节点,然后迭代所有节点,每2切换一次。我的第二次尝试是具有基本情况检查是否存在 0 或 1 个节点的递归解决方案。然后我交换了前 2 个节点,然后递归遍历链表的其余部分,然后加入链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || (head.next == null)){return head;}
//first we swap the first node and the second node
ListNode first = head;
ListNode third = head.next.next;
first.next.next = first;
first.next = third;
//then we recurse on part of the linked list
ListNode recursedList = swapPairs(head.next.next);
//we join these two linked lists together
first.next.next = recursedList;
//and finally we return the head
return head;
}
}
对于示例输入
[1,2,3,4] 解决方案是
[2,1,4,3] 但我的解决方案产生 [1,3,4]。我的代码在哪里我的逻辑有缺陷?
【问题讨论】:
-
你需要递归吗?
-
@RustyCore 是的,这个问题是一个面试问题,需要我给出一个递归实现。我很好奇是否有更有效的方法来成对交换节点?
标签: java recursion linked-list