[LeetCode] 24. Swap Nodes in Pairs 交换相邻结点 @python
2018-03-18 13:45
609 查看
Description
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->3->4,你应该返回 2->1->4->3。
你的算法应该只使用额外的常数空间。不要修改列表中的值,只有节点本身可以更改。
Solution
核心点:另加一个头结点。注意指向顺序!# -*- coding: utf-8 -*- """ Created on Sat Mar 17 20:55:41 2018 @author: Saul """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(0) dummy.next = head pre, cur = dummy, head while cur and cur.next: pre.next = cur.next # 0->2 cur.next = pre.next.next # 1->3 pre.next.next = cur pre = cur cur = cur.next return dummy.next
相关文章推荐
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- leetcode_24. Swap Nodes in Pairs 单链表中成对交换结点位置
- leetcode-24,交换链表相邻节点,递归实现
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- leetcode24,交换链表相邻的节点
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- [Leetcode] Swap nodes in pairs 成对交换结点
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- LeetCode 24. Swap Nodes in Pairs(按对交换单链表结点)
- 指针p,q,r依次指向某循环链表中三个相邻的结点,交换结点*q,*r在表中次序的程序段是
- 双链表交换相邻结点
- 习题3.3---只通过调整指针来达到相邻结点交换的过程
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- LeetCode算法练习(交换相邻结点)
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- java 交换链表中所有相邻结点的顺序
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)