Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
来源:互联网 发布:万象域名 编辑:程序博客网 时间:2024/06/18 15:55
一、题目叙述:
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.
Subscribe to see which companies asked this question
二、解题思路:
easy题,非常简单,不要想着交换链表的指针,交换值就行了。
(1)之后在做完题后,把最基本的例子跑一遍,不要再写死循环了!
三、源码:
/** * 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) { ListNode a = head; int temp; if (head == null) return null; while (a.next != null) { temp = a.next.val; a.next.val = a.val; a.val = temp; if (a.next.next != null) a = a.next.next; else a = a.next; } return head; } public void print(ListNode root) { System.out.print(root.val + "\t"); if (root.next != null) print(root.next); } public static void main (String args[]) { ListNode l1 = new ListNode(2); ListNode a = l1; a.next = new ListNode(3); a = a.next; a.next = new ListNode(4); a = a.next; a.next = new ListNode(1); //b.next = new ListNode(4); Solution s = new Solution(); s.print(s.swapPairs(l1)); }}
0 0
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- Swap Nodes in Pairs 成对交换结点
- [LeetCode]Swap Nodes in Pairs 成对交换
- leetcode_24. Swap Nodes in Pairs 单链表中成对交换结点位置
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- leetcode——Swap Nodes in Pairs 旋转链表中相邻成对数字(AC)
- [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-------24. Swap Nodes in Pairs(两两交换)
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- 判断一个数字是否为质数。
- eclipse使用mybatis做查询时条件有汉字的不能执行成功
- 树莓系统安装+网络(杂记)
- 设计模式第一天 策略模式
- bzoj1222 [HNOI2001]产品加工
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- iOS label文字添加中划线和下划线
- Linux系统sersync数据实时同步
- php时间计算
- 单精度浮点数 二进制的转换 C++实现
- Mybatis增删改查以及Dao的写法
- ListView设置onItemCLickListener监听时获取的position不正确问题
- 适时把自己归零
- 请编写一个C函数,该函数将一个字符串逆序