Swap Nodes in Pairs
2015-11-28 22:33
691 查看
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.
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.
/** * 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* res,*p,*q; if(head==NULL||head->next==NULL) return head; res=head->next; head->next=res->next; res->next=head; while(head->next!=NULL&&head->next->next!=NULL) { q=head; head=head->next; p=head->next; q->next=p; head->next=p->next; p->next=head; } return res; } };
相关文章推荐
- ROS_hydro_catkin建立标准程序包_helloworld.h+helloworld.cpp+helloworldnode.cpp
- NodeManagerMetrics上精确化Container指标监控
- NodeJS中使用benchmark进行基准测试-@alsotang
- nodejs学习--子进程 child_process模块的基本介绍
- nodejs学习--util
- nodej-- Query String
- A new node couldn't be inserted because one with the same name exists. (VERR_CFGM_NODE_EXISTS)
- nodejs学习--path
- [转][自己打脸]Node.JS——NodeJS引用路径的小问题
- nodejs-url
- nodejs学习1---基础知识
- node 可视化调试(支持监控文件变化)
- nodejs 快速实现url图片重定向
- java.lang.IllegalArgumentException: node to traverse cannot be null!
- HDFS NameNode主要内部结构
- 11.28 mac node-sublime text环境配置
- 第一篇Node.js+React相关总结整理
- nodejs 像 C 语言那样输出当前代码的行数
- NodeJS(三) Mac下 require 路径访问
- Nodejs-使用 promise 替代回调函数