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