LeetCode解题报告--Swap Nodes in Pairs
来源:互联网 发布:手机网络管理软件 编辑:程序博客网 时间:2024/06/05 19:48
题目:
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.
原题:https://leetcode.com/problems/swap-nodes-in-pairs/
分析:题意要求将给定的链表,相邻的结点交换位置,并返回变化后的链表。
基本思路利用指针移位法,注意考虑特殊情况,如链表为空,链表长度为0,1,2等。
如下图是思路的示意:
不同颜色表示不同次的循环过程。
java代码 Accepted:
/** * 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 p; ListNode q; ListNode k; p = head; q = p.next; k = q.next; head = head.next; while (q != null) { q.next = p; if(k != null && k.next != null){ p.next = k.next; p = k; q = k.next; k = k.next.next; }else{ p.next = k; q = null; k = null; } /*p = k; if(k != null){ q = k.next; }else{ q = null; } if(k != null && k.next != null){ k = k.next.next; }else{ k = null; }*/ } return head; }}
0 0
- LeetCode解题报告--Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- Swap Nodes in Pairs LeetCode 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- [Leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- leetcode解题报告24. Swap Nodes in Pairs
- [leetcode javascript解题]Swap Nodes in Pairs
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- Swap Nodes in Pairs ——解题报告
- leetcode解题方案--024--Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- ZMQ的初步学习
- 条理清晰的搭建SSH环境之整合Struts和Spring
- html5中sql 使用
- 共享一些毕业设计论文
- 众筹出版《介绍用Java编程》一书
- LeetCode解题报告--Swap Nodes in Pairs
- 条理清晰的搭建SSH环境之整合Hibernate和Spring
- uboot 显示nandflash中的图片
- Quarts 示例2
- SQL AUTO INCREMENT 字段 高级教程
- 大数据的排序策略
- 实现截屏并存储在本地
- 第十二章 二叉搜索树
- html5d的indexDB使用