328. Odd Even Linked List——多利用fake_head
2024-08-30 03:19:12
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:
Given 1->2->3->4->5->NULL
,
return 1->3->5->2->4->NULL
.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = head
i = 1
odd_fake, even_fake = ListNode(None), ListNode(None)
odd_tail, even_tail = odd_fake, even_fake
while node:
if i & 1:
odd_tail.next = node
odd_tail = node
else:
even_tail.next = node
even_tail = node
node = node.next
i += 1
even_tail.next = None
odd_tail.next = even_fake.next
return odd_fake.next
最新文章
- jquery双击事件
- java获取客户端ID地址
- swift 2.x学习笔记(二)
- 复旦大学2014--2015学年第二学期高等代数II期末考试情况分析
- 集合框架,ArrayList和Vector的区别,让arrayList线程安全的几种方案
- Win8 安装驱动
- AWS 之Load Balance篇
- 我眼中的go的语法特点
- CTE-递归[2]
- C:\WINDOWS\system32\config\systemprofile\Desktop引用了一个不可用的位置
- 《程序设计语言——实践之路(英文第三版)》【PDF】下载
- 【CF715E】Complete the Permutations 第一类斯特林数
- ES6 Symbol数据类型和set-map 数据结构
- Mad Lids游戏 华氏与摄氏温度转换
- Django之MVC和MTV
- mongodb 通过mongodump来备份Sharded Cluste分片集群
- python垃圾回收三之标记清除
- Minix2.0操作系统公用头文件说明
- maven+testng+reportng的pom设置
- FileZilla提权的过程