<LeetCode OJ> 24. Swap Nodes in Pairs
2016-05-29 16:12
537 查看
Total Accepted: 99965 Total
Submissions: 281854 Difficulty: Easy
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Subscribe to see which companies asked this question
Hide Tags
Linked List
Hide Similar Problems
(H) Reverse Nodes in k-Group
分析:
如同链表的逆转一样,本题是三指针遍历,注意整个过程的规律即可,特别要注意不但要交换两个节点,还要连接前一对节点,比如2->1->3->4,把3和4交换后,1实际上并没有指向4,程序中通过pPre指针记录了节点1,将其连接交换后的4!具体见代码!
<LeetCode
OJ> 206. Reverse Linked List
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51532493
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:/article/3664871.html
Submissions: 281854 Difficulty: Easy
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.
Subscribe to see which companies asked this question
Hide Tags
Linked List
Hide Similar Problems
(H) Reverse Nodes in k-Group
分析:
如同链表的逆转一样,本题是三指针遍历,注意整个过程的规律即可,特别要注意不但要交换两个节点,还要连接前一对节点,比如2->1->3->4,把3和4交换后,1实际上并没有指向4,程序中通过pPre指针记录了节点1,将其连接交换后的4!具体见代码!
<LeetCode
OJ> 206. Reverse Linked List
/** * 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|| head->next==NULL ) return head; ListNode* pPre=head; ListNode* pcurSwap1=head; ListNode* pcurSwap2=head->next; head=head->next; while(pcurSwap1!=NULL && pcurSwap2!=NULL) { //连接链表 pPre->next=pcurSwap2; //交换当前节点 pcurSwap1->next=pcurSwap2->next; pcurSwap2->next=pcurSwap1; //准备下一对(必须均存在) pPre=pcurSwap1; pcurSwap1=pcurSwap1->next; if(pcurSwap1!=NULL) pcurSwap2=pcurSwap1->next; } return head; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51532493
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:/article/3664871.html
相关文章推荐
- 24. Swap Nodes in Pairs [easy] (Python)
- RabbitMQ 基础教程(1) - Hello World
- nodejs抓取网页的源码,并保存到本地文件
- 《Nodejs开发加密货币》之十六:利益,魔鬼与天使的共同目标
- Hello Hexo
- 安装Node和NPM
- nodejs安装
- leetcode 24 Swap Nodes in Pairs C++
- mybatis---源码分析----xml解析----XNode
- Node.js中文API
- nodejs学习笔记
- C++的性能优化实践 map hash_map unodered_map性能
- 如何设计 Node.js
- 认识Node.js中流
- leetcode 116. Populating Next Right Pointers in Each Node-递归|非递归
- 零星记录Nodejs,NPM,express等小知识
- node.js 版本升级
- Node.js 的优势和劣势都有哪些
- Hadoop格式化namenode错误:java.io.IOException: Cannot create directory
- 我的NodeJS一年之旅总结