leetcode-24-Swap Nodes in Pairs
2016-05-19 21:50
495 查看
题目:iven 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.
交换链表每两个元素的位置。
思路:
1.出现单个的情况链表不变
2.链表为空或者只有一个元素,返回head头指针即可。
3.需要一个p保存开始的头指针,在不为空时p=head->next。最后返回p->next。
3.需要一个pre指针指向每次交换完成后最后的那个node。移动head,交换完成后将pre指向head->next。
具体见图。解释了while(head->next)和if(q->next)时的情况每一步做了什么。
4ms AC。
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
交换链表每两个元素的位置。
思路:
1.出现单个的情况链表不变
2.链表为空或者只有一个元素,返回head头指针即可。
3.需要一个p保存开始的头指针,在不为空时p=head->next。最后返回p->next。
3.需要一个pre指针指向每次交换完成后最后的那个node。移动head,交换完成后将pre指向head->next。
具体见图。解释了while(head->next)和if(q->next)时的情况每一步做了什么。
/** * 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==NULL || head->next==NULL) return head; ListNode* p=new ListNode(0); p->next=head->next; ListNode* pre=p; ListNode* q=head->next; while(head->next){ q=head->next; if(q->next){ head->next=q->next; q->next=head; head=head->next; pre->next=q; pre=q->next; } else{ head->next=NULL; q->next=head; pre->next=q; } } return p->next; } };
4ms AC。
相关文章推荐
- nodejs学习心得
- NodeJS学习笔记
- nodejs Controller层 封装
- nodejs npm
- nodejs中module.exports和exports.xx的区别
- node socket onmessage
- Hadoop 2.0 Yarn代码:NodeManager端代码分析_NM端各服务模块的启动
- 在windows环境下基于sublime text3的node.js开发环境搭建(转)
- Failed to obtain address information for hostname mynode1: Name or service not known
- Windows下安装node及基本操作
- nvm 管理你的nodejs版本
- Node.mongoose
- leetcode 之Reverse Nodes in k-Group(22)
- Node.js+Express配置入门教程详解
- leetcode 之Swap Nodes in Pairs(21)
- leetcode 之Remove Nth Node From End of List(19)
- heroku快速部署node应用
- nodejs+phantomjs+七牛 实现截屏操作并上传七牛存储
- 关于node.js的安装与删除
- NodeMCU介绍