博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swap Nodes in Pairs
阅读量:4583 次
发布时间:2019-06-09

本文共 1047 字,大约阅读时间需要 3 分钟。

24. Swap Nodes in Pairs

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.

 to see which companies asked this question

思路:设置一个头结点,每俩个节点倒置一下

/** * 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 *ans=new ListNode(0);          ans->next=head;          ListNode *cur=ans;          while(cur && cur->next && cur->next->next){              ListNode *first=cur->next;        	  ListNode *second=first->next;        	  ListNode *three=second->next;        	  first->next=three;        	  second->next=first;        	  cur->next=second;        	  cur=first;           }          return ans->next;        }};

转载于:https://www.cnblogs.com/zhanpang/p/5682850.html

你可能感兴趣的文章
一对一关系
查看>>
git命令的使用 【备用】
查看>>
uva1391 2-SAT 问题
查看>>
数据类型
查看>>
Java秒杀系统实战系列~整合Shiro实现用户登录认证
查看>>
js功能汇总
查看>>
C. Magic Ship cf 二分
查看>>
Android(java)学习笔记107:Relativelayout相对布局
查看>>
leetcode[90]Subsets II
查看>>
hlg1175小陈老师、桌子、盘子【计算几何】
查看>>
SSH服务器拒绝了密码,xshell连不上虚拟机怎么办
查看>>
Swoole RPC 的实现
查看>>
动态规划求两个序列的最长公共子序列
查看>>
课堂随笔
查看>>
阿里巴巴代码规范阅读记录
查看>>
冲刺2-4
查看>>
[bbk4774] 第30集 - 第三章 Flashback Table 07
查看>>
MD5 加密 以及 加盐加密
查看>>
十一:Centralized Cache Management in HDFS 集中缓存管理
查看>>
C#中使用MD5加密的方法
查看>>