0
点赞
收藏
分享

微信扫一扫

leetcode---链表类型---每日一题

邯唐情感 2022-02-27 阅读 43

题目 第22题,合并有序链表


题解思路


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        """
            1、考虑两个链表的情况:
                list1 ---> []
                list2 ---> []
                return list1

                list1 ---> ![]
                list2 ---> []
                return list1

                list1 ---> []
                list2 ---> ![]
                return list2

            2、思路
            遍历两个链表的同时,比较大小,然后让大的在后面,小的在前面 
            

            3、遇到的问题,
                如何遍历?
                    因为题目给的是一个节点,所以设置两个工作变量 P1 和 p2, p1 = list1, p2 = list2
                    while(p1 && p2):
                        if(p1.val <= p2.val):
                            # 衔接
                        else:
                            # 衔接

                是否需要新生成一个链表,大小为len(list1)+len(list2)?
                    最后返回的是一个头结点,那可以生成一个new_head 然后让new_head.next = list1
                    最后返回new_head.next就行

                如果两个链表都不是空,且长度不一样,当遍历完后一个链表,剩下的怎么进行处理?

                if(p1 is None):
                    # 将链表与list2衔接起来
                
                if(p2 is None):
                    # 将链表与list1衔接起来

        """

        # 特殊情况
        if list1 is None and list2 is None:
            return None
        
        # 冗余部分
        # if list1 is None and list2:
        #     return list2

        # if list1 and list2 is None:
        #     return list1

        # 生成新的头结点
        new_head = ListNode(-1, list1)
        print(new_head.val)

        # 三个工作指针
        p1, p2, p3 = list1, list2, new_head

        # 遍历
        while p1 and p2:
            if p1.val <= p2.val:
                # 当p1的值比p2的值小的时候, 先让p3.next指向p1,然后p1向后移动
                p3.next = p1
                p1 = p1.next
            else:
                p3.next = p2
                p2 = p2.next
            p3 = p3.next
        
        # 处理长短不一的情况

        # 可以简洁
        # if p1 is None:
        #     p3.next = p2
        
        # if p2 is None:
        #     p3.next = p1
        p3.next = p2 if p1 is None else p1

        return new_head.next
        
        """
            运行时出错情况:
                按照上述思路运行,结果时间超时!考虑问题出现哪里,猜测是while循环这里出错
                    原因:if else 中 p3 = p1 和 p3 = p2出错
                    我想的是让p3向后移,但是上述代码语句是让p3直接变了,链表会断开

                    解决方法在if else执行完后,再开始用P3 = p3.next


            查看代码是否有冗余部分
                有冗余部分, 注释部分

            
            查看代码是否可以简洁部分
            	可以
        """



举报

相关推荐

0 条评论