Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这道题目要求你只能使用常数个空间,你不能修改链表中的值,只能让节点自己变化,也就是变动其位置。由于这道题目画图感觉不直观,我在下面做了一个模拟程序运行步骤的注释,方便自己和大家理解。
package com.alibaba.learning;
public class Solution
{
public ListNode swapPairs(ListNode head)
{
if (head == null)
return null;
if (head.next == null)
return head;
ListNode temp = head.next;
head.next = swapPairs(temp.next);
temp.next = head;
return temp;
}
}
/**
* 以1->2->3->4为例模拟算法运行,首先保存链表中第二个节点,它在新的链表中必定是一个新的头结点;
* head.next = swapPairs(temp.next)传过去的是3->4,开始调用自身,作用就是后面的链表可以交换
* {
* 判断语句跳过;
* ListNode temp = head.next; 此时temp指向4;
* head.next = swapPairs(null); 开始调用自身,
* {
* 执行第一条判断语句,返回了null,即就是3->null;
* }
* temp.next = head; 此时4->3->null;
* return temp;返回了一个4->3->null的链表
*
* }以上执行完之后, 1->4->3->null
* temp.next = head; 此时2->1->4->3->null
* return temp;返回最后的链表;
*
*/