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

思路:

1.(头二个节点已经事先处理)找出要换位置的两个节点的前驱节点,设为tempHead,设要更换的两个节点为p,q

2.那么直接p节点拿出,tempHead->next=q;p->next=NULL;

3.然后就是普通把p几点插入到q节点后面即可。p->next=q->next;q->next=p;

4.最后把暂时头部节点后移两个位置,进行下一次更换。

图解如下:

代码:

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* res;
if(head==NULL) return NULL;
if(head->next==NULL) return head;
//交换第一,二个节点
ListNode* first=head->next;
head->next=first->next;
first->next=head; ListNode* tempHead=first->next;
ListNode* p;
ListNode* q;
while (tempHead)
{
if(tempHead->next!=NULL&&tempHead->next->next!=NULL){
p=tempHead->next;
q=tempHead->next->next;
}
else return first; tempHead->next=q;
p->next=NULL;//中间节点插入即可 p->next=q->next;
q->next=p;
tempHead=q->next; }
return first;
}
};

最新文章

  1. 深度解析C语言int与unsigned int
  2. HandlerThread 创建一个异步的后台线程
  3. AOP实现原理
  4. TypeC一个微软开发的超简单.NET依赖注入/IoC容器
  5. ODBC接口规范
  6. PHP生成随机字符串包括大小写字母
  7. python学习第三天第一部分
  8. virtualbox共享文件夹无访问权限问题解决方法
  9. java与数据结构(3)---java实现循环链表
  10. QF——OC中的KVC,KVO
  11. deepin2014.1安装搜狗后却找不到图标及配置
  12. Sublime 3 打造成 Python/Django IDE开发利器
  13. 四.RabbitMQ之发布/订阅(Publish/Subscribe)
  14. hadoop+hive+spark搭建(二)
  15. 如何在eclipse中添加ADT
  16. Flask的Windows部署:mod_wsgi + Apache
  17. 一、Tableau基础
  18. 【python】bytes与字符串的相互转化
  19. [转]XSS的原理分析与解剖:第四章(编码与绕过)
  20. Java transient关键字的理解

热门文章

  1. AJPFX关于数组获取最值的思路和方法
  2. (一)Spring之初了解
  3. linux小白成长之路11————​linux命令大全
  4. 开源项目:JEECG
  5. 微信小程序组件解读和分析:九、form表单
  6. VBox虚拟机安装debian
  7. webpack3.0版本的一些改动
  8. Activiti数据库表结构(表详细版)
  9. Discuz3.1登录QQ互联显示redirect uri is illegal(100010)的解决
  10. Oracle反向字符截取逗號分隔字符串