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