【Java】LeetCode进阶之路(Swap Nodes in Pairs)
来源:互联网 发布:vb format函数 编辑:程序博客网 时间:2024/05/21 08:50
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.
题目;根据给出的例子,可以很容易理解题意,把一个链表每两个节点调换位置。
思路:链表位置不好调换,所以先把这个数据放到一个数组里,这样就容易换位置了,换完之后在输出新的链表即可。
public class Solution { public ListNode swapPairs(ListNode head) { List<Integer> list = new ArrayList<Integer>(); ListNode node = new ListNode(0); ListNode h = node; while(head != null){ list.add(head.val); head = head.next; } int[] nums = new int[list.size()]; for(int i = 0; i<list.size();i = i+2){ if(i + 1 > list.size() -1) { nums[i] = list.get(i); }else { nums[i] = list.get(i+1); nums[i+1] = list.get(i); } } for(int i = 0;i < nums.length;i++){ ListNode n = new ListNode(nums[i]); h.next = n; h = h.next; } return node.next; }}
7.26更新
这道题目涉及到链表,肯定是希望用指针的思想来做,下面这种方法就是用到了指针,通过指针指向不同的位置来更换节点的顺序。
<span style="font-size:18px;">public ListNode swapPairs(ListNode head) { if(head == null) return null; if(head.next == null) return head; ListNode first = new ListNode(-1); first.next = head; ListNode ptr1 = first; ListNode ptr2 = first.next; while(ptr1 != null && ptr2 != null && ptr2.next != null) { ListNode nextNode = ptr2.next.next; ptr1.next = ptr2.next; ptr1.next.next = ptr2; ptr2.next = nextNode; ptr1 = ptr2; ptr2 = nextNode; } return first.next; }</span>
0 0
- 【Java】LeetCode进阶之路(Swap Nodes in Pairs)
- leetcode之Swap Nodes in Pairs
- LeetCode 之 Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- 【LeetCode】之Swap Nodes in Pairs
- 【Leetcode】之Swap Nodes in Pairs
- leetcode之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 Swap Nodes in Pairs java实现
- [LeetCode][Java] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs [java]
- 24. Swap Nodes in Pairs -leetcode-java
- (Java)LeetCode-24. Swap Nodes in Pairs
- POJ 3126 Prime Path(素数变换路径)
- 解决thinkPHP3.2.3使用Smarty模板后无法使用系统常量问题
- 十道海量数据处理面试题与十个方法大总结
- APP输入法测试点
- ButterKnife框架使用详解
- 【Java】LeetCode进阶之路(Swap Nodes in Pairs)
- C++——C和C++,面向对象三大特性,程序开发过程(1)
- windows下python的NumPy、SciPy、matplotlib安装
- scala基础25-闭包
- js倒计时(每个小时特定时间抽奖)
- 多多的故事
- HDU 1506 Largest Rectangle in a Histogram(最大矩形面积、单调栈)
- Java NIO学习
- 使用FFmpeg4android 实现视频 水印 剪切 压缩 旋转