美文网首页
[LeetCode By Python] 328. Odd Ev

[LeetCode By Python] 328. Odd Ev

作者: 乐乐可爱睡觉 | 来源:发表于2016-06-13 17:09 被阅读112次

一、题目

LeetCode By Python

二、解题

题意是先把奇数位置数字链起来,然后后面再接偶数位。

  1. 首先初始化node r,赋值head,去遍历整个链表
  2. 然后有一个指针r2,去储存第二个位置的node(此时是head->next,但是最后赋值回来的时候不能使用head->next,因为后面head就是新的链表了)
  3. 还需要一个指针last,去标示r的上一个值,因为需要根据times,来判断到底是last还是r指向偶数的第一个。

三、尝试与结果

class Solution(object):
    def oddEvenList(self, head):
        if head == None:
            return None
        times = 0
        last = ListNode(0)
        t = ListNode(0)
        r2 = head.next
        r = head
        while r.next != None:
            last = r
            t = r.next
            r.next = r.next.next
            r = t
            times += 1
        if times %2 == 1:
            last.next = r2
        else:
            r.next = r2
        return head

结果:AC

相关文章

网友评论

      本文标题:[LeetCode By Python] 328. Odd Ev

      本文链接:https://www.haomeiwen.com/subject/cfvydttx.html