[LwwtCode]24. Swap Nodes in Pairs
来源:互联网 发布:sql注入绕过waf 编辑:程序博客网 时间:2024/06/05 19:03
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.
思路:交换链表的前两个节点 p1,p2,保存pnext = p2.next;交换后为p2,p1,p1.next = swap(pnext);即递归调用交换链表前两个节点的方法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode res = new ListNode(0); res.next = head; ListNode p1 = res.next; ListNode p2 = res.next.next; ListNode pnext = res.next.next.next; res.next = p2; p2.next = p1; p1.next = swapPairs(pnext); return res.next; } }
0 0
- [LwwtCode]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
- Intersection of Two Linked Lists
- css 动画 transition及animation
- 用PyMOL制作分子结构图像及所用脚本
- 同步问题
- IOS中字符串三种相加方法(转)
- [LwwtCode]24. Swap Nodes in Pairs
- 爬虫技术:(JavaScript渲染)动态页面抓取超级指南
- Android Studio添加assets文件夹
- java -abstract详解
- jquery中append与appendTo方法区别
- ceph存储 CentOS系统启动流程及GRUB文件说明
- java基础之反射
- Ubuntu 12.04之找不到Qemu命令
- Javascript获取经纬度,关于调用百度API的问题