コード例 #1
0
ファイル: Reorder List.py プロジェクト: chyt123/cosmos
 def reorderList(self, head: Optional[ListNode]) -> None:
     """
     Do not return anything, modify head in-place instead.
     """
     pt = head
     pre = dict()
     cnt = 1
     while pt.next:
         pre[pt.next] = pt
         pt = pt.next
         cnt += 1
     # now pt is the last node
     # print(cnt)
     pt2 = head
     cnt = (cnt + 1) // 2
     while cnt > 1:
         pt.next = pt2.next
         pt2.next = pt
         pt2 = pt.next
         pt = pre[pt]
         cnt -= 1
     pt.next = None
     print(lc_singlelinkedlist2list(head))
コード例 #2
0
from typing import List
from util import ListNode, lc_list2singlelinkedlist, lc_singlelinkedlist2list


class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        rtn = head
        while head:
            if head.next and head.val == head.next.val:
                nxt = head.next
                head.next = head.next.next
                del nxt
            else:
                head = head.next
        return rtn


if __name__ == "__main__":
    sol = Solution()
    test_cases = [
        [1, 1, 2, 3, 3],
        [1, 1, 1, 2, 2, 3],
    ]
    for i in test_cases:
        i = lc_list2singlelinkedlist(i)
        result = sol.deleteDuplicates(i)
        print(lc_singlelinkedlist2list(result))
コード例 #3
0

class Solution:
    def insertionSortList(self,
                          head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(-5001)
        dummy.next = to_insert = head
        while head and head.next:
            if head.val > head.next.val:
                to_insert = head.next
                pre = dummy
                while pre.next.val < to_insert.val:
                    pre = pre.next
                head.next = to_insert.next
                to_insert.next = pre.next
                pre.next = to_insert
            else:
                head = head.next
        return dummy.next


if __name__ == "__main__":
    sol = Solution()
    test_cases = [
        [4, 2, 1, 3],
        [-1, 5, 3, 4, 0],
    ]
    for i in test_cases:
        dummyult = sol.insertionSortList(lc_list2singlelinkedlist(i))
        print(lc_singlelinkedlist2list(dummyult))