24. Swap Nodes in Pairs
2016-03-28 00:08
661 查看
1.Question
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.
2.Code
3.Note
a. 这个题两个数一组处理就好了,例如:abc的顺序,则先让a指向c, b指向a。然后进入到下一组的两个数。还有就是要更新上一组的数字指向当前组交换后的数字,以及第一次交换的特殊处理。
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.
2.Code
/** * 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 *p1 = head, *p2 = head->next, *p3; head = head->next; while(p2) { p1->next = p2->next; p2->next = p1; if(head != p2) p3->next = p2; p3 = p1; p1 = p1->next; if(p1) p2 = p1->next; else p2 = NULL; } return head; } };
3.Note
a. 这个题两个数一组处理就好了,例如:abc的顺序,则先让a指向c, b指向a。然后进入到下一组的两个数。还有就是要更新上一组的数字指向当前组交换后的数字,以及第一次交换的特殊处理。
相关文章推荐
- 新手如何快速入门node.js
- zookeeper实现namenode的高可用(HA)(第三篇)
- 利用zookeeper来实现namanode的高可用(HA)(第二篇)
- Leetcode #25 Reverse Nodes in k-Group K区间链表交换 解题报告
- 剖析NodeJs的事件轮询机制
- zookeeper环境的搭建,来实现namenode的高可用(HA)(第一篇)
- 通用node.js环境搭建
- Nodejs开发(1.Sublime Text 3配置)
- 深入浅出nodejs学习笔记——nodejs简介
- 用node.js对一个英语句子分析页面进行一个小爬虫
- 10最好用的Node.js工具、插件和资料库
- 命令passwd报错因inode节点处理记录
- (二)electron 文件系统访问
- 如何搭建一个简单的本地node.js服务器
- NodeJs - 序列化
- NodeJs - 100
- MindNode Pro serial number
- (一)Electron入门介绍
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- PAT (Advanced Level) Practise 1115 Counting Nodes in a BST (30)