LeetCode代码记录 24 Swap Nodes in Pairs
来源:互联网 发布:戈尔巴乔夫 知乎 编辑:程序博客网 时间:2024/06/11 09:59
题目如下:
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.
这道题主要还是链表的互换,比较简单,答案运行官方Case时间为4ms,仍有很多提升空间。/** * 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* nextPointer = head; ListNode* pPre = NULL; ListNode* pSwap = NULL; while(nextPointer!=NULL && nextPointer->next!=NULL) { if( nextPointer == head) { pSwap = nextPointer->next; nextPointer->next = pSwap->next; head = pSwap; pSwap->next = nextPointer; } else { pSwap = nextPointer->next; nextPointer->next = pSwap->next; pPre->next = pSwap; pSwap->next = nextPointer; } pPre = nextPointer; nextPointer = nextPointer->next; } return head; }};
0 0
- LeetCode代码记录 24 Swap Nodes in Pairs
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- google glog使用
- jvm命令之jstat
- 游戏中聊天 栏简单 思想
- 解读DSI405中的enqueue之:哈希和闩
- 深入浅出 - Android系统移植与平台开发(四)- 搭建Linux编译环境
- LeetCode代码记录 24 Swap Nodes in Pairs
- spring 7 bean配置--spEL
- CentOS 6.6安装Tomcat 7
- 剑指Offer-面试题22:栈的压入、弹出序列
- printf fprintf perror区别
- Android推送技术研究
- 改变imageButton按下和抬起时的bac…
- Java关键字介绍之this与super
- 安卓控件及控件属性