24. Swap Nodes in Pairs (java实现)

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;返回最后的链表;
 *
*/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值