在Leecode 练习递归时,遇到以下题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
要注意不能只交换结点的值,而是要交换结点,交换结点的值则实现更加容易。
输出示例为:
给定1->2->3->4
, 你应该返回2->1->4->3
.
试着实现代码:
private static ListNode helper(ListNode head,ListNode head1,ListNode temp){
if(head1==null){
return null;
} else if(head1.next==null){
return head1;
}
if(head1.next!=null){
temp=head1.next;
head1.next=head1.next.next;
temp.next=head1;
}
if(head==null){
head=temp;
}
helper(head,head1.next,temp);
return head;
}
测试的结果却并不如人意,输出的内容总是为第一次修改后的链表,后面递归程序对链表的修改尽管实行了,但是没有在原链表进行修改,一番思考,发现问题出现在 链表的值传递方法
众所周知,一般对象的传递方法分为按值传递和按地址传递,按值传递与按地址传递在这里就不赘述了,若上面程序是按地址传递,则运行结果应该是正确的,因为就算递归处没有进行连接,其按地址传递会直接与原地址相连,不会导致断链。
首先想到了JAVA中的深拷贝与浅拷贝,于是查看之前做的笔记:
Java核心技术【卷一】——学习笔记(五)
发现并不适合本题使用,于是在网上一番搜罗,发现一个递归的范例:
Recursive mutator methods follow a pattern in which they return a reference to the mutated linked list (instead of being void); such a generalization allows for a simple recursive implementation of the method. This approach takes a bit of getting used to, but it is a pattern that is used repeatedly here and in the recursive processing of tree with mutators. In the following method, it used used to return a reference to the linked list l, in which a new node containing value is inserted at its rear.
public static LN insertRear (LN l, int value) {
if (l == null) {
return new LN(value,null);
} else {
l.next = insertRear(l.next, value);
return l;
}
}
参考来源:https://www.cs.cmu.edu/~pattis/15-1XX/15-200/lectures/llrecursion/index.html
关键代码为:
l.next = insertRear(l.next, value);
使用 l.next=递归程序 便能将数组成功连接起来,从而实现数组的连接
完整的程序代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode temp=new ListNode(0);
ListNode t=head;
head=null;
head=helper(head,t,temp);
return head;
}
private static ListNode helper(ListNode head,ListNode head1,ListNode temp){
if(head1==null){
return null;
} else if(head1.next==null){
return head1;
}
if(head1.next!=null){
temp=head1.next;
head1.next=head1.next.next;
temp.next=head1;
}
if(head==null){
head=temp;
}
head1.next=helper(head,head1.next,temp);
return temp;
}
}