Swap Nodes in Pairs
2015-06-11 15:51
477 查看
题目:
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.
解题思路:
这题主要涉及到链表的基本操作。加一个头结点,操作起来会很方便。另外配了一个示意图
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
sentry_node = ListNode(0)
sentry_node.next = head
pre,suc = sentry_node,head
while (suc and suc.next):
pre.next = suc.next
suc.next = pre.next.next
pre.next.next = suc
pre, suc = suc,suc.next
return sentry_node.next
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.
解题思路:
这题主要涉及到链表的基本操作。加一个头结点,操作起来会很方便。另外配了一个示意图
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
sentry_node = ListNode(0)
sentry_node.next = head
pre,suc = sentry_node,head
while (suc and suc.next):
pre.next = suc.next
suc.next = pre.next.next
pre.next.next = suc
pre, suc = suc,suc.next
return sentry_node.next
相关文章推荐
- nodejs 安装express
- nodejs 学习资料
- nodejs 安装
- nodejs fs.open
- Initialization failed for block pool Block pool <registering> (Datanode Uuid unassigned) service
- Leetcode[222]-Count Complete Tree Nodes
- node.js 标准/错误输出 和 process.exit
- nodejs模块加载机制
- win7下安装node及出现的npm问题
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- LeetCode 之 Swap Nodes in Pairs — C 实现
- 学习nodejs——callback, async i/o
- 【Leetcode Algorithm】Remove Nth Node From End of List
- Ubuntu 11.10 H3C iNode 客户端安装
- ERROR: Can't get master address from ZooKeeper; znode data == null
- leetcode之Count Complete Tree Nodes
- 推荐15个 Node.js 开发工具
- Format aborted in 格式化namenode 失败的原因
- [LeetCode] Count Complete Tree Nodes 求完全二叉树的节点个数
- Count Complete Tree Nodes