Leetcode Swap Nodes in Pairs 交换链表的节点对
来源:互联网 发布:谷歌有哪些好软件? 编辑:程序博客网 时间:2024/06/03 13:43
题目:
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.
分析:
1. 首先考虑链表是空或者只有一个节点,直接返回链表。
2. 链表的头节点一定会发生改变,因此使用dummy node。
3. 需要三个指针,一个指向需要交换的节点对的前一个节点,一个指向第一个需要交换的节点,最后一个指向第二个需要交换的节点
Java代码实现:
/** * 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 dummy = new ListNode(0); ListNode node = dummy; ListNode first = head; ListNode second = head.next; while(second!=null) { ListNode temp = second.next; node.next = second; node.next.next = first; node = node.next.next; node.next = temp; first = node.next; if(first!=null) second = first.next; else second = first; } return dummy.next; }}
0 0
- Leetcode Swap Nodes in Pairs 交换链表的节点对
- Swap Nodes in Pairs 链表交换相邻的节点
- [LeetCode]Swap Nodes in Pairs 交换节点
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- Swap Nodes in Pairs 交换LinkList的相邻节点
- [LeetCode]Swap Nodes in Pairs 成对交换
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- 【LeetCode】Swap Nodes in Pairs 链表指针的应用
- Swap Nodes in Pairs --成对交换链表节点(重重重)
- 451.Swap Nodes in Pairs-两两交换链表中的节点(容易题)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Codeforces Round #299 (Div. 2)B. Tavas and SaDDas
- easyui小计
- POJ2785——4 Values whose Sum is 0
- Vijos P1110 小胖邮递员(HNOI2004)题解
- Web安全篇之SQL注入攻击
- Leetcode Swap Nodes in Pairs 交换链表的节点对
- 【已解决】tomcat报严重: Socket accept failed
- 加密:DigestUtils与java MessageDigest
- 【leetcode】Add Binary
- 解决Linux系统中缺少Xvfb包的问题
- [刷题]Convert Sorted List to Binary Search Tree
- jQuery.extend 函数详解
- redis学习笔记
- java基本数据类型的多重转型