1. 程式人生 > >資料結構與演算法解題:合併兩個有序連結串列

資料結構與演算法解題:合併兩個有序連結串列

資料結構和演算法,是程式設計的基礎,想要提高程式設計能力,這是繞不開的坎,為了練習演算法,在Codewars和LeetCode上刷了一些難度級別為easy的題,程式碼都儲存成py檔案了,時間久了,積累的多了,有些亂,接下了打算逐步把它們搬到部落格上來,整理一下,便於查詢複習。廢話少說,開工!

試題

1、將兩個有序連結串列合併為一個新的有序連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。
示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

解題思路:

1,建立一個新的空連結串列k;
2,對2個單向連結串列(a,b)進行遍歷,逐個取出所有的元素進行對比;
3,a[1]>b[1],則把b[1]加入k,往後走到b[2],再和a[1]對比,大,則新增a[1]到k的尾部,一直迴圈對比,把較小的值新增到k的尾部,如果相等,則都新增;
4,直到a和 b有一個到達尾部,或者同時到達尾部,若只有一個到達尾部,則遍歷另一個連結串列,把裡面的元素逐個加入到k的尾部,
2個同時到達尾部,則結束,返回k

解題程式碼:

這道題邏輯很清晰,麻煩的地方在於連結串列並不像列表一樣,是內建的資料型別,可以使用list方法直接建立,需要自己手動建立
首先要建立連結串列節點及方法,並新增一些資料

class ListNode:
	"""
	建立節點
	"""
    def __init__(self, x):
        self.val = x
        self.next = None
        

建立連結串列的方法
這裡只需要新增元素方法和遍歷方法(最後檢視用)就可以了,

class SingleLinkList:
    def __init__(self):
        self._head = None

    def append(self, item):
        """尾部新增元素"""
        node = ListNode(item)
        # 先判斷連結串列是否為空,若是空連結串列,則將_head指向新節點
        if self.is_empty():
            self._head = node
            node.next = None
        # 若不為空,則找到尾部,將尾節點的next指向新節點
        else:
            cur = self._head
            while cur.next != None:
                cur = cur.next

            cur.next = node

    def is_empty(self):
        """判斷連結串列是否為空"""
        return self._head == None

    def travel(self):
        """遍歷連結串列"""
        if self.is_empty():
            return
        cur = self._head
        print('cur.val',cur.val)
        while cur.next != None:
            cur = cur.next
            print('cur.val', cur.val)    
 

合併連結串列程式碼

class Solution():
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 建立新連結串列
        newnode = SingleLinkList()
        cur1 = l1._head
        cur2 = l2._head
        while (cur1 != None) and (cur2 != None):
            if cur1.val < cur2.val:
                newnode.append(cur1.val)
                cur1 = cur1.next
            elif cur1.val > cur2.val:
                newnode.append(cur2.val)
                cur2 = cur2.next
            else:
                newnode.append(cur1.val)
                newnode.append(cur2.val)
                cur1 = cur1.next
                cur2 = cur2.next
        else:
            if cur1 == None:
                while cur2 != None:
                    newnode.append(cur2.val)
                    cur2 = cur2.next

            elif cur2 == None:
                while cur1 != None:
                    newnode.append(cur1.val)
                    cur1 = cur1.next

        return newnode

驗證結果

建立連結串列,並新增元素(注意:因為要求是有序連結串列,所以新增元素時要按順序)
if __name__ == "__main__":
	sl1 = SingleLinkList()
	sl1.append(2)
	sl1.append(6)
	sl1.append(9)
	sl1.append(14)
	sl1.append(36)
	
	sl2 = SingleLinkList()
	sl2.append(3)
	sl2.append(8)
	sl2.append(9)
	sl2.append(12)
	sl2.append(22)
	sl2.append(35)
	
	# 呼叫函式,result接收返回值
	res = Solution()
	result = res.mergeTwoLists(sl1, sl2)
	# 遍歷驗證
	result.travel()

遍歷結果:
cur.val 2
cur.val 3
cur.val 6
cur.val 8
cur.val 9
cur.val 9
cur.val 12
cur.val 14
cur.val 22
cur.val 35
cur.val 36