Swap Nodes in Pairs
来源:互联网 发布:软件注册过期怎么办 编辑:程序博客网 时间:2024/06/06 13:14
题目:
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
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Zookeeper -- leader选举
- 一个初中生,是怎么做到工资过万的?
- 关于Android 选择相册图片裁剪的坑
- 二、TIPTOP命名原则和目录配置—TIPTOP GP ERP二次开发新手教程
- 2015.6.11 TEST
- Swap Nodes in Pairs
- GRE issue写作6分模板
- java-从先序遍历和中序遍历重建二叉树
- CSS3 transform实现图片投影效果
- MimeType.exe 使 ActiveX 对象标签可以使用Mime type=application
- MVC大型商贸系统(库存管理)技术解释(四) 商品调拨
- HashSet剖析
- xml解析出现的错误
- 插入排序