swap-nodes-in-pairs(单链表交换点对)
2017-04-10 21:57
225 查看
题目描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
/** * Definition for singly-linked list. * 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; 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; } }
相关文章推荐
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- Swap Nodes in Pairs --成对交换链表节点(重重重)
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- LeetCode | Swap Nodes in Pairs(将链表中的元素两两交换)
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- Swap Nodes in Pairs 链表交换相邻的节点
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- 451. 两两交换链表中的节点(swap-nodes-in-pairs)(c++)----lintcode面试题之链表
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- 【链表&交换邻节点】Swap Nodes in Pairs
- [LeetCode][链表]Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- Swap Nodes in Pairs(交换一对结点)
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- 【leetcode】【单链表】【24】Swap Nodes in Pairs