LeetCode_24_Swap Nodes in Pairs
来源:互联网 发布:模拟电路软件汉化版 编辑:程序博客网 时间:2024/05/18 22:42
题目描述
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.
个人感想
操作链表的时候完全可以建一个新的头结点,这样在处理边界问题的时候非常方便
代码实现
class Solution { public ListNode swapPairs(ListNode head) { if (head == null) return null; if (head.next == null) return head; ListNode fakeHead = new ListNode(0); fakeHead.next = head; ListNode currentNode = fakeHead; while (currentNode.next != null && currentNode.next.next != null) { ListNode first = currentNode.next; ListNode second = currentNode.next.next; first.next = second.next; second.next = first; currentNode.next = second; currentNode = currentNode.next.next; } return fakeHead.next; }}
阅读全文
0 0
- Leetcode_24_Swap Nodes in Pairs
- leetcode_24_Swap Nodes in Pairs
- leetcode_24_Swap Nodes in Pairs
- LeetCode_24_Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- 理解 IntelliJ IDEA 的项目配置和Web部署
- 经典编程书籍大全
- 预习 for 循环的使用和数组的概念
- 利用Dom4j 解析XML文件
- linux c编程操作数据库(sqlite3应用)
- LeetCode_24_Swap Nodes in Pairs
- Android 开发资料便签
- 我如何在5台虚拟机上整合hadoop生态圈的各种组件(随笔)
- 【python】 string.puntuation符号匹配原则
- Why Stackable Switches Are More Favored?
- Runloop 探秘(二)—— NSTimer 计时不准?
- CentOS7安装Maven编译pom所出的异常
- 欢迎使用CSDN-markdown编辑器
- C++编译的若干问题