Python-剑指offer(13,14)调整数组顺序使奇数置于偶数前面,链表中倒数第k个节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35164554/article/details/82700629

题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

环境:Python2.7.3

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        i = 0
        count = 0
        while i <len(array):
            if array[i] % 2 == 0:
                array.append(array.pop(i))
                i-=1
            i+=1
            count+=1
            if count ==len(array):
                break
        return array
                
                

题目:输入一个链表,输出该链表中倒数第k个结点。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head or k == 0:
            return None
        thead = head
        for i in range(k-1):
            if thead.next != None:
                thead = thead.next
            else:
                return None
        while thead.next != None:
                head = head.next
                thead = thead.next
        return head
            
            

猜你喜欢

转载自blog.csdn.net/qq_35164554/article/details/82700629
今日推荐