leetcode笔记--Swap Nodes in Pairs
2016-02-19 15:59
579 查看
题目:难度(Medium)
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.
Tags:Linked List
Similar Problems:(H) Reverse Nodes in k-Group
分析:关键是用指针记录下几个关键位置,若q指向要交换的第一个节点,则要交换的节点是q与q.next,那么需要记录的还有q的前驱结点p,和q.next的后继节点r
代码实现:
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.
Tags:Linked List
Similar Problems:(H) Reverse Nodes in k-Group
分析:关键是用指针记录下几个关键位置,若q指向要交换的第一个节点,则要交换的节点是q与q.next,那么需要记录的还有q的前驱结点p,和q.next的后继节点r
代码实现:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head #如果head至少有2个节点,就需要有交换操作 #先交换前2个 p = head head = head.next p.next = head.next head.next = p #交换第3个节点开始的剩余链表部分 while p.next is not None: q = p.next if q.next is not None: r = q.next.next p.next = q.next q.next.next = q q.next = r p = q return head
相关文章推荐
- 用nodejs 开发的智能提示
- nodejs开发cms系统之开篇
- leetcode:Swap Nodes in Pairs
- Node.js 之Buffer缓冲区
- nodejs学习笔记一
- nodejs学习路线图
- leetcode笔记--Delete Node in a Linked List
- node.js学习笔记之babel使用
- NodeJS中使用swig模板引擎
- node学习之第一个接口,简单的登录验证
- leetcode笔记--Remove Nth Node From End of List
- LeetCode - 25. Reverse Nodes in k-Group
- Node.js
- LeetCode - 24. Swap Nodes in Pairs
- namenode fsimage edits
- node查询mySql表
- windows下node.js环境配置
- [Nodejs] 记录一个小坑:Can't set headers after they are sent
- node递归属性目录结构
- node递归属性目录结构