24. Swap Nodes in Pairs [easy]
来源:互联网 发布:王者荣耀mvp 详细算法 编辑:程序博客网 时间:2024/05/15 23:54
题目:
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.
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode swapPairs(ListNode head) { if(head==null||head.next==null) return head; ListNode pre = new ListNode(0); ListNode dummy = pre, cur = head, post = cur.next; pre.next = head; while(post!=null){ cur.next = post.next; post.next = cur; pre.next = post; pre = cur; cur = cur.next; if(cur==null) break; post = cur.next; } return dummy.next; }}
Python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ dup=ListNode(0); dup.next=head;p=dup while p.next!=None and p.next.next!=None: temp=p.next p.next=temp.next p=p.next temp.next=p.next p.next=temp #关键 p=temp return dup.next
0 0
- 24. Swap Nodes in Pairs [easy]
- 24. Swap Nodes in Pairs [easy] (Python)
- 24.LeetCode Swap Nodes in Pairs(easy)[单链表]
- Leetcode 24. Swap Nodes in Pairs (Easy) (cpp)
- Swap Nodes in Pairs(easy)
- Swap Nodes in Pairs (EASY)
- Easy 24题 Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- shader 编程模块化开发的一些方法
- RecyclerView Part 1:为ListView专家写的基础
- 2016百度之星 资格赛 1002 Problem B 递推加大数
- 34 Spark中任务处理的Stage划分和Task最佳位置算法
- Hongyang 生命不息,奋斗不止,万事起于忽微,量变引起质变 目录视图 摘要视图 订阅 Android 属性动画(Property Animation) 完全解析 (上)
- 24. Swap Nodes in Pairs [easy]
- RecyclerView Part 2:选择模式
- Java基础中常犯的一些细节上的错误
- 图像数据到网格数据-2——改进的SMC算法
- Google:坚决杀死Flash
- 图像数据到网格数据-3——Cuberille算法
- SM2算法第十篇:数字证书及CA的扫盲介绍
- UNIX网络编程:IPC之信号量
- 针对大数据的种子点生长——分块生长的策略