【LeetCode】Swap Nodes in Pairs 解题报告
2024-10-19 19:56:52
Swap Nodes in Pairs
[LeetCode]
https://leetcode.com/problems/swap-nodes-in-pairs/
Total Accepted: 95332 Total Submissions: 270806 Difficulty: Easy
Question
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.
Ways
最讨厌的就是这种指针来回走的题!
先是自己定义了一个头部,然后first指向这个头部answer,然后next指向链表的第一个元素。因为要把前两个元素翻转,所以用after保存第三个元素。
然后就是一系列翻转,我老是搞错。。好囧。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode answer=new ListNode(0);
answer.next=head;
ListNode first=answer;
ListNode next=answer.next;
ListNode after;
while(next!=null && next.next!=null){
after=next.next.next;
next.next.next=next;
first.next=next.next;
next.next=after;
first=next;
next=after;
}
return answer.next;
}
}
AC:1ms
Date
2016/5/1 20:24:22
最新文章
- WebGIS项目中利用mysql控制点库进行千万条数据坐标转换时的分表分区优化方案
- C语言辗转相除法求2个数的最小公约数
- [LeetCode] Valid Parentheses 验证括号
- struts.xml
- C# 生成windows 服务打包程序
- Java 日期格式化工具类
- vnc 登录后只有终端 没有桌面 黑屏
- LeetCode 笔记28 Maximum Gap
- php中命名空间的使用
- 轻松大幅度降低 Meteor App 的首屏加载时间
- gitignre
- debug(fmt,args...)调试
- ViewController详解
- Linux部署ASP.NET 5 (vNext)
- word中批量转换字母数字为Times New Roman
- docker 中打包部署Springboot项目
- loj.ac:#10024. 「一本通 1.3 练习 3」质数方阵
- OGNL表达式的一个坑!
- hive数据导出到本地目录 抛异常
- 【repost】javascript:;与javascript:void(0)使用介绍