#451 Swap Nodes in Pairs
来源:互联网 发布:js 指定时间转时间戳 编辑:程序博客网 时间:2024/06/07 13:23
题目描述:
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Challenge
题目思路:Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这题继续用好用的dummy head,然后就是指针swap,需要注意的是swap过程中的顺序。
Mycode(AC = 31ms):
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: /** * @param head a ListNode * @return a ListNode */ ListNode* swapPairs(ListNode* head) { // Write your code here ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *tmp = dummy, *next = dummy->next; while (next && next->next) { tmp->next = next->next; next->next = tmp->next->next; tmp->next->next = next; tmp = next; next = tmp->next; } return dummy->next; }};
0 0
- #451 Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Selenium框架源码解析-1 PageFactory
- Servlet的一点零碎知识
- 测试人员如何搭建自动打包部署平台?(具体详细步骤及下载地址)
- 在Mac上搭建Nginx服务器(视频直播)
- 55. Jump Game(重要)
- #451 Swap Nodes in Pairs
- session的个人理解
- 混合现实VR Twitch视频
- solr中DIH关于Oracle数据中clob类型字段的配置
- IOS实战 (2) 之 环形渐变色 进度展示条
- Problem 1011 Rikka with Parenthesis II
- 字符串以及字符串的操作
- Oracle伪列rownum
- 欢迎使用Markdown编辑器写博客