博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode328. Odd Even Linked List(思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 986 字,大约阅读时间需要 3 分钟。

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example 1:

Input: 1->2->3->4->5->NULLOutput: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULLOutput: 2->3->6->7->1->5->4->NULL

把奇数位置节点连在一起,再把偶数位置节点连在一起,再把这两个链表连在一起。

思路就是新建两个节点dummy1和dummy2。

然后不断遍历head,分别连接偶数位置和奇数位置的节点。

思路比较简单,注意偶数节点最后要设置even.next=None即可

class Solution:    def oddEvenList(self, head: ListNode) -> ListNode:                dummy1=even=ListNode(0)        dummy2=odd=ListNode(0)                while head:            odd.next=head            odd=odd.next            head=head.next            if head:                even.next=head                even=even.next                head=head.next        even.next=None        odd.next=dummy1.next                return dummy2.next

 

转载地址:http://sjrbb.baihongyu.com/

你可能感兴趣的文章
BaseServiceImpl中的实现关键点
查看>>
Struts2中的session、request、respsonse获取方法
查看>>
如何理解MVC模型
查看>>
SpringMVC中乱码解决方案
查看>>
SpringMVC中时间格式转换的解决方案
查看>>
post和get请求相关知识点
查看>>
关于try finally 中的return语句的问题
查看>>
RequestBody/ResponseBody处理Json数据
查看>>
springmvc请求参数获取的几种方法
查看>>
在eclipse中创建和myeclipse一样的包结构
查看>>
Java中的IO流
查看>>
java中的关键字
查看>>
如果某个方法是静态的,它的行为就不具有多态性
查看>>
优化Hibernate所鼓励的7大措施
查看>>
Java 8系列之重新认识HashMap
查看>>
HashMap 、 ArrayList、String 重写了equals方法 而Object类(比如User)没有重写
查看>>
Servlet的生命周期
查看>>
Object中的getClass()返回的是当前运行的类
查看>>
加载驱动程序的方法
查看>>
深入理解java异常处理机制
查看>>