leetcode 24 swapPairs
来源:互联网 发布:adams数据导出 编辑:程序博客网 时间:2024/06/18 00:30
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.
/** * 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 dummy(INT_MIN); ListNode *tail = &dummy; ListNode *first = head; while (first != NULL) { ListNode *second = first->next; if (second == NULL) break; ListNode* tmp = second->next; second->next = first; tail->next = second; tail = first; first = tmp; } // odd numbers tail->next = first ? first : NULL; return dummy.next; }}; // runtime contribution 25.86%
参考后
I. 指针
/** * 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) { typedef ListNode* Node; Node *p = &head; Node first = NULL; Node second = NULL; while ((first = *p) && (second = first->next)) { first->next = second->next; second->next = first; *p = second; p = &(first->next); } return head; }}; // runtime contribution 25.86%
II. 递归
/** * 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) { if (head == NULL) return NULL; if (head->next == NULL) return head; ListNode* first = head, *second = head->next; first->next = second->next; second->next = first; first->next = swapPairs(first->next); return second; }}; // runtime contribution 25.86%
阅读全文
0 0
- leetcode 24 swapPairs
- swapPairs
- leetcode-24
- LeetCode #24
- [LeetCode] Climbing Stairs [24]
- LeetCode (24) Happy Number
- 2015.8.24-LeetCode
- leetcode #24 in cpp
- leetCode练习(24)
- (java)leetcode-24
- LeetCode 21-24
- [Leetcode] 24, 25, 138
- 24 game [LeetCode 679]
- [LeetCode]679. 24 Game
- LeetCode刷题(24)
- leetcode
- [leetcode]
- LeetCode
- 4.3.2深度定时任务(TimerTask in Depth)
- 线程池学习笔记
- 如何成为一个及格的码农
- 剑指offer_第一个只出现一次的字符
- 常用图片格式介绍(了解
- leetcode 24 swapPairs
- from google.protobuf.internal import enum_type_wrapper ImportError: No module named google.protobuf
- 【Android】Android性能优化
- 设计模式之享元模式
- Unity5实战使用C#和Unity开发多平台游戏pdf
- 4.4总结
- 时间类型的转换
- [Android][第一行代码][第 5 章 广播机制]
- dubbo服务提供者暴露一个服务的详细过程