24. 两两交换链表中的节点
因为说不能改变结点内部的值 感觉我这种方法不是很可靠
/**
* 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 = head;
int temp1 = -1;
int temp2 = -1;
while(temp!=null&&temp.next!=null){
temp1 = temp.val;
temp2 = temp.next.val;
temp.val = temp2;
temp.next.val = temp1;
temp = temp.next.next;
}
return head;
}
}
重复同一个行为采用递归
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}