【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
来源:互联网 发布:centos 6.4 厂家 编辑:程序博客网 时间:2024/06/05 16:55
【024-Swap Nodes in Pairs(成对交换单链表的结点)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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.
题目大意
给定一个单链表,成对交换两个相邻的结点。算法法应该做常量辅助空间,不能改结点的值,只能交换结点。
解题思路
使用一个头结点root来辅助操作,对要进行交换的链表,每两个的位置进行交换,并且把交换后的结点接到root的链表上,直到所有的结点都处理完。
代码实现
结点类
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}
算法实现类
public class Solution { public ListNode swapPairs(ListNode head) { ListNode node = new ListNode(0); // 头结点 node.next = head; // p指向新的链表的尾结点 ListNode p = node; ListNode tmp; // 每两个进行操作 while (p.next != null && p.next.next != null) { // 记录下一次要进行处理的位置 tmp = p.next.next; // 下面三句完成两个结点交换 p.next.next = tmp.next; tmp.next = p.next; p.next = tmp; // 指向返回链表的新的尾结点 p = tmp.next; } head = node.next; node.next = null; return head; }}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47034975】
2 0
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- Swap Nodes in Pairs 成对交换结点
- [LeetCode]Swap Nodes in Pairs 成对交换
- leetcode_24. Swap Nodes in Pairs 单链表中成对交换结点位置
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- leetcode Swap Nodes in Pairs java实现
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- [LeetCode]Swap Nodes in Pairs 交换节点
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- Swap Nodes in Pairs --成对交换链表节点(重重重)
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- K - Perpetuum Mobile
- IP网络,光网络以及轨道交通的高速卸载随想
- Dallas one-wire temperature reading on BeagleBone Black with dto (未翻译)
- Sqoop 1.99.3 安装
- C#__Dictionary类 __类似java Map 键值对
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- Android中popupWindow的简单应用
- 设置圆角按钮的方法
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- Objective-C之KVC(键值编码)详解
- solr5.2.1环境搭建
- 杭电ACM2032java做法
- 如何在中关村做好一门小生意——北漂18年(18)