Swap Nodes in Pairs -- leetcode
来源:互联网 发布:php面向对象编程 pdf 编辑:程序博客网 时间:2024/04/30 11:31
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,借助临时变量作交换
在leetcode上执行时间为8ms。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *swapPairs(ListNode *head) { ListNode fake(0); ListNode *prev = &fake; while (head && head->next) { ListNode *bak = head->next->next; prev->next = head->next; head->next->next = head; prev = head; head = bak; } prev->next = head; return fake.next; }};
在写法一的基础上,去掉了临时变量bak。
此算法在leetcode上执行时间为12ms。
class Solution {public: ListNode *swapPairs(ListNode *head) { ListNode fake(0); fake.next = head; ListNode *prev = &fake; while (head && head->next) { prev->next = head->next; head->next = head->next->next; prev->next->next = head; prev = head; head = head->next; } return fake.next; }};
总结,算法2比算法1少用了一个临时变量。
个人更喜欢写法1,因为写法1的临时变量bak,编译器很容易用一个寄存器来表示。相比算法2,少了一次内存写访问操作。
这大概是写法1的执行时间比写法2更快的原因。
0 0
- 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
- 人类会微调的地方大同小异,不就泪沟跟双颊
- NGUI系列教程二
- 滚动的盒子
- NGUI系列教程三
- 分享三个photoshop小脚本(JavaScript)
- Swap Nodes in Pairs -- leetcode
- Objective-C打印BOOL型变量
- poj 1321 棋盘问题(回溯)
- ios中的视图调试(ios8苹果引入了强大的新技术,不可不看)
- 爸爸妈妈,我想你们了
- java中struts2中配置struts.xml的package
- 8.3(2)多分支函数求值(switch语句)
- 有趣的指针
- Swift-结构体