Swap Nodes in Pairs
2015-06-14 20:36
555 查看
Description:
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.
Code:
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.
Code:
ListNode* swapPairs(ListNode* head) { if (!head) return NULL; ListNode *preNode = new ListNode(0); preNode ->next = head; ListNode *m_preNode = preNode; ListNode *p = head; ListNode *q = p->next; while (p&&q) { preNode->next = q; p->next = q->next; q->next = p; preNode = p; p = preNode->next; //要注意检测p是否为空值,否则对q赋值就会出现错误 if (p) q = p->next; else q = NULL; } return m_preNode->next; }
相关文章推荐
- 文件系统(一)--super.c bitmap.c inode.c 源码分析
- Swap Nodes in Pairs
- 19 Remove Nth Node From End of List(去掉链表中倒数第n个节点Easy)
- 一晚上 -- Populating Next Right Pointers in Each Node II
- [Node.js] 对称加密、公钥加密和RSA
- Node.js学习--基础知识(4)--模块与包
- Node.js学习--基础知识(3)--回调函数与事件
- node.js 初体验
- Node.js学习--基础知识(2)--异步IO与事件式编程
- LeetCode 24:Swap Nodes in Pairs
- Nodejs部署再思考
- nodejs中express安装失败解决方法
- 深入浅出NodeJS笔记(一)
- Swap Nodes in Pairs
- LeetCode 之 Remove Nth Node From End of List — C++ 实现
- Count Complete Tree Nodes
- 24-m-Swap Nodes in Pairs
- Leetcode: Reverse Nodes in k-Group
- node.js发送邮件
- leetCode:Count Complete Tree Nodes