leetcode python 21. 合并两个有序链表 83. 删除排序链表中的重复元素

https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
本质是合并排序的merge,只不过这里用了所谓的链表结构,一开始不之地数据类型是NodeList,拿普通的python列表写半天,过程很简答,只要比较两个链表中当前值,小的放入第三个链表中,并把指针后移,直到某一链表为空,把非空的链表接到第三个链表上就可以。

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

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        L = []
        while (1):
            if l1==None or l2==None:
                break
            if (l1.val <= l2.val):
                L.append(l1.val)
                l1=l1.next
            else:
                L.append(l2.val)
                l2=l2.next
        if l1==None:
            while(l2!=None):
                L.append(l2.val)
                l2=l2.next
        elif l2==None:
            while (l1 != None):
                L.append(l1.val)
                l1 = l1.next
        return L

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
这题也是对python中的链表进行操作,所以特意放一起了,就是数据结构中简单的链表操作。

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

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if(head==None):
            return None
        p=head
        while (p.next != None):
            if(p.val==p.next.val):
                p.next=p.next.next
            else:
                p=p.next
        return head

你可能感兴趣的:(Leetcode)