(LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
2016-09-06 22:42
483 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
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
解题分析:
对于此题目,分析题目,我们可以加一个索引,在第一个结点,然后可以保证第一个结点不丢失, 然后依次交换每个结点。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur and cur.next:
pre.next = cur.next
cur.next = pre.next.next
pre.next.next = cur
pre, cur = cur, cur.next
return dummy.next
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
解题分析:
对于此题目,分析题目,我们可以加一个索引,在第一个结点,然后可以保证第一个结点不丢失, 然后依次交换每个结点。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur and cur.next:
pre.next = cur.next
cur.next = pre.next.next
pre.next.next = cur
pre, cur = cur, cur.next
return dummy.next
相关文章推荐
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
- LeetCode 24. Swap Nodes in Pairs(按对交换单链表结点)
- [Leetcode] Swap nodes in pairs 成对交换结点
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- LeetCode-------24. Swap Nodes in Pairs(两两交换)
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- [LintCode] Swap Two Nodes in Linked List 交换链表中的两个结点
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- Swap Nodes in Pairs 链表交换相邻的节点