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.

/**
* 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 *h = (ListNode*)malloc(sizeof(struct ListNode));
h->next=head;
ListNode *s,*p,*q,*tmp;
s=h;
//两个节点中,p作为第一个节点,s是p前一个节点
p=s->next;
while(p){
//q作为第二个节点
q=p->next;
if(!q)
break;
p->next=q->next;
s->next=q;
q->next=p; s=p;
p=p->next;
}
p=h->next;
free(h);
return p;
}
};

最新文章

  1. 【BO】SAP BO相关问题汇总贴
  2. epoll里面mmap释疑
  3. Android开发学习之路-抢红包助手开发全攻略
  4. IOS8 空项目全屏
  5. Ruby on Rails Tutorial 第二章 之 用户资源&MVC&REST
  6. 【转】Java自动装箱、拆箱、缓冲池
  7. SSH隧道技术----端口转发,socket代理
  8. mysql的分页存储过程,能够传出总记录数
  9. 鼠标相关操作(Cursor类及相关API)
  10. 【朝花夕拾】四大组件之(二)Service篇
  11. [二]基础数据类型之Long详解
  12. windows安装虚拟机(VMware)
  13. Java中String直接赋字符串和new String的区别(面试常考)
  14. uva 103(最长递增子序列) Stacking Boxes
  15. intellij idea 2016.3.5 控制台取消行数限制
  16. css实现div不定宽高垂直水平居中解决方案
  17. h5 微场景
  18. Wahrscheinlichkeitstheorie und mathematische Statistik
  19. 屏蔽F1~F12的快捷键的js函数
  20. Kylin 几个sql报错原因 汇总

热门文章

  1. ffmpeg-20160929-bin.7z
  2. NIO及Reactor模式
  3. android学习第一篇 基本概念
  4. 10.OC中retainCount返回值不准的原因
  5. tp框架的增删改查
  6. Redis的Python实践,以及四中常用应用场景详解——学习董伟明老师的《Python Web开发实践》
  7. js对象克隆方法
  8. java中的多线程
  9. winform进程、线程、TreeView递归加载
  10. PHP常用函数、数组方法