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 …
题意:给一单链表,奇-偶-奇-偶-…..,不改变奇偶的原始顺序,输出奇-奇-偶-偶-……,不能改变结点的值,时间复杂度为o(n),空间复杂度为0(1)
思路:提取奇数链表和偶数链表,然后拼接即可
方法一:偶数链表新建一个头结点,主要是要注意最后一位是偶数还是奇数
Runtime: 112 ms
方法二:偶数链表需要设置头结点用于拼接,注意停止循环的条件,与方法一不同,
Runtime: 75 ms
方法二优于方法一
方法一:
# 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):
if not head or not head.next:
return head
p=head
deven=ListNode(0)
p1=deven
while p.next and p.next.next:
p1.next=p.next
p.next=p.next.next
p=p.next
p1=p1.next
if p.next:
p1.next=p.next
else:
p1.next=None
p.next=deven.next
return head
方法二:
class Solution(object):
def oddEvenList(self, head):
if not head or not head.next:
return head
p1=head
p2=evenhead=head.next
while p2 and p2.next:
p1.next=p1.next.next
p1=p1.next
p2.next=p2.next.next
p2=p2.next
p1.next=evenhead
return head