24. Swap Nodes in Pairs
来源:互联网 发布:周立功单片机笔试题目 编辑:程序博客网 时间:2024/06/05 18:34
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.
题目要求:不能改变节点内的值,只能改变节点的位置。方法1:
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode swap=head;
ListNode t=null;
ListNode h=head;
t=swap.next;
swap.next=t.next;
t.next=swap;
head=t;
while(swap.next!=null&&swap.next.next!=null){
h=swap;
swap=swap.next;
t=swap.next;
swap.next=t.next;
t.next=swap;
h.next=t;
}
return head;
}
}
方法2:
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){return head;
}
ListNode slow = head;
ListNode fast = head.next;
slow.next = fast.next;
fast.next = slow;
head = fast;
slow.next = swapPairs(slow.next);
return head;
}
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 使用关键帧动画实现转圈
- spring mvc 使用及json 日期转换解决方案
- 更改ITunes 备份目录
- Centos下安装JDK和Mysql
- ios通过SQLite自定义缓存数据
- 24. Swap Nodes in Pairs
- jedis 操作cluster以及故障演示
- 创建一个推荐程序
- ssm初步
- windwos下调度kettle任务
- Odoo - Testing Modules
- 用DCOS和marathon-lb实现服务发现和负载均衡:第一部分
- 109之今日学习
- AutoLayout VFL 笔记