(LeetCode)鏈表

1. 反轉鏈表

206. reverse-linked-list
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode

        笨辦法
        1. 遍歷鏈表,生成一個數組;
        2. 根據數組,倒序創建鏈表;

        聰明辦法
        改指針方向
        """
        cur = head
        pre = None
        while cur is not None:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        return pre

2. 合併兩個有序鏈表

21. merge-two-sorted-lists
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode

        笨辦法:
        遍歷兩個鏈表,得到數組;將數組排好序;生成一個新的鏈表;

        聰明解法:
        遞歸
        """
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        if l1.val >= l2.val:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章