Swap Nodes in Pairs -- LeetCode
来源:互联网 发布:手机淘宝6.10旧版本 编辑:程序博客网 时间:2024/06/18 06:15
原题链接: http://oj.leetcode.com/problems/swap-nodes-in-pairs/
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。实现中注意细节就可以了,不过我发现现在面试中链表操作的题目出现并不多,所以个人觉得大家练一下就好了,不用花太多时间哈。
这道题属于链表操作的题目,思路比较清晰,就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)。代码如下:
public ListNode swapPairs(ListNode head) { if(head == null) return null; ListNode helper = new ListNode(0); helper.next = head; ListNode pre = helper; ListNode cur = head; while(cur!=null && cur.next!=null) { ListNode next = cur.next.next; cur.next.next = cur; pre.next = cur.next; if(next!=null && next.next!=null) cur.next = next.next; else cur.next = next; pre = cur; cur = next; } return helper.next;}这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。实现中注意细节就可以了,不过我发现现在面试中链表操作的题目出现并不多,所以个人觉得大家练一下就好了,不用花太多时间哈。
57 1
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- OSG一个terrain相机
- 写给linux系统管理员看的systemd 二 给定Service拥有哪些进程(systemd作者blog翻译过来的)
- [LeetCode] 4Sum
- xml,json,txt
- 凌晨1点半
- Swap Nodes in Pairs -- LeetCode
- win7中VS2010中安装CSS3.0问题解决方法
- uboot源码中start.S里中断向量表中不直接LDR PC ,"异常地址",而是使用一个标号
- [Unity3d]刀斧武器砍击的攻击碰撞判定
- 【整理】关于角色攻击范围判定和攻击判定
- java算法面试题-----1
- Longest Substring Without Repeating Characters -- LeetCode
- codeforces#231_div2_B Very Beautiful Number 高精度枚举
- ldr和adr在使用标号表达式作为操作数的区别