Swap Nodes in Pairs
2015-08-14 00:42
549 查看
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.
Solution:
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.
Solution:
/** * 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 || !head->next) return head; ListNode* lead = new ListNode(-1); lead->next = head; ListNode *p = lead, *tmp; while(head && head->next) { tmp = head->next; head->next = head->next->next; tmp->next = head; p->next = tmp; head = head->next; p = p->next->next; } return lead->next; } };
相关文章推荐
- nodejs 输出 html 标签
- LeetCode——Count Complete Tree Nodes
- [leetcode] Delete Node in a Linked List 删除链表中的一个结点
- nodejs中module.exports和exports比较
- hadoop1.2.1集群增加datanode节点
- [leetcode] Remove Nth Node From End of List 删除链表开始的第n个元素
- nodejs中两种定义函数的方法
- node配合Express4 创建项目
- NodeJs使用json web token验证REST服务
- node 关于项目中post和get方式的参数接收方法总结
- nodejs co generator 调用另外一个generator
- node 不是内部命令或外部命令
- 第二章. node中的模块和require
- [leetcode]Delete Node in a Linked List
- 第一章 Nodejs 介绍及安装
- LeetCode 24 Swap Nodes in Pair
- 启动hadoop时报错,nodemanager running as process 6410. Stop it first.解决方法
- nodejs co 本质学习 及演进代码
- 深入浅出Node.js(五):初探Node.js的异步I/O实现
- node 利用crypto进行hash加密和URLSafeBase64处理 (node.js邮箱验证)