Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given1->2->3->4, you should return the list as2->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.

题意:成对交换结点。

思路:这题感觉是reverse nodes in k grops的是一个特殊情况。这题更简单一些,只要保证当前结点cur和其后继存在就可以交换。改变表头,所以要new一个。代码如下:

 /**
* 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 *nList=new ListNode(-);
nList->next=head;
ListNode *pre=nList;
ListNode *cur=head; while(cur&&cur->next)
{
ListNode *temp=cur->next;
cur->next=temp->next;
temp->next=pre->next;
pre->next=temp;
pre=cur;
cur=cur->next;
} return nList->next;
}
};

最新文章

  1. 创建一个ArcGIS for Android 新项目并显示出本地的地图
  2. QT学习笔记2
  3. j$(function() j$(document).ready 区别
  4. 10.Java设计模式 工厂模式,单例模式
  5. Umbraco Forms 使Rendering Forms scripts 在不同的template中
  6. 微信网页授权java实现
  7. 新鲜出炉的less与sass较量
  8. LINUX读写文件区别
  9. c#多线程,进度条,实时给前台发送数据
  10. Dynamics CRM2016 Web API之Retrieve Multiple
  11. Python学习摘要201802
  12. 花点时间顺顺Git(上)
  13. Json字符串转map集合
  14. Expo大作战(三十三)--expo sdk api之MapView(地图),MailComposer(磁力传感计),Lottie(动画)
  15. Hadoop【单机安装-测试程序WordCount】
  16. Resolve类中错误体系的处理
  17. Class does not Implement Equals——Code Correctness(代码正确性)
  18. OpenGL学习(2)——绘制三角形(补)
  19. 关于django-rest-freamwork中的View
  20. python2 python3 字符串 编码格式 处理

热门文章

  1. Python学习手册之Python介绍、基本语法(二)
  2. phpcms2008网站漏洞如何修复 远程代码写入缓存漏洞利用
  3. GIT LFS 使用笔记
  4. PHP.38-TP框架商城应用实例-后台14-商品管理-商品扩展分类的删除、修改
  5. Hadoop:WordCount分析
  6. 环境变量 - JDK
  7. 在Go语言里检测内存泄漏
  8. 【数据结构】 Queue 的简单实现
  9. (干货分享)mac python+appium环境搭建
  10. 关于python的闭包与装饰器的实验