1. 程式人生 > >Leetcode之鏈表(前200道)

Leetcode之鏈表(前200道)

ica div eth color exc type rmi 鏈表 res

Easy

1. Merge Two Sorted Lists:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

這道題有兩種解法,一種是iterator,一種是recursively

iterator:

# 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 """ result=current=ListNode(0) if not l1: return l2 if
not l2: return l1 while l1 and l2: if l1.val<l2.val: current.next=l1 l1=l1.next else: current.next=l2 l2=l2.next current=current.next current.next=l1 or l2 return
result.next

recursively:

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1: 
            return l2
        if not l2:
            return l1
        if l1.val==l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            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(l2.next,l1)
            return l2

這道題用了兩種方法:recursively和iterator。 recursively比較難理解,畫出stack模型會比較容易理解,主要是通過反復調用方法來實現。 iterator比較容易理解,主要思想是創造兩個新的鏈表,result和current,current負責存儲通過比較l1和l2得出的結果的節點, result負責最後的返回,result=current=ListNode(0)。要註意:每次比較完之後,要用l1=l1.next來移動到下一個節點進行比較 同時,每一次循環最後都需要current=current.next來移動到下一個節點。當l1或者l2的節點為none時,跳出循環,使用current.next=l1orl2 來將另外一個節點剩余節點存入current,最後return result.next

2. Remove Duplicates from Sorted List:

Given a sorted linked list, delete all duplicates such that each element appear only once.

# 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
        """
        current=head
        if not current:
            return None
        while current.next:
            if current.next.val==current.val:
                current.next=current.next.next
            else:
                current=current.next
        return head
1.single-linked list的head不是空
2.最後返回是return head,可以返回整個list

3. Linked List Cycle:
Given a linked list, determine if it has a cycle in it.
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        try:
            slow=head
            fast=head.next
            while slow is not fast:
                slow=slow.next
                fast=fast.next.next
            return True
        except:
            return False
            
            
        
這道題要mark一下
很有意思的算法,設了兩個指針,一個快指針,一個慢指針,快指針每次.next.next,慢指針.next,用了try...except,如果是有cycle的話,
慢指針和快指針總會遇到,於是返回true
如果沒有(except),返回false
4.Intersection of Two Linked Lists:
Write a program to find the node at which the intersection of two singly linked lists begins.
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        a=headA
        b=headB
        if a is None or b is None:
            return None

        while a is not b:
            if a is None:
                a=headB
            else:
                a=a.next
            if b is None:
                b=headA
            else:
                b=b.next
        return a
    

這個算法也要mark一下!很機智!
核心就是指向兩個鏈表節點的指針一起移動,但是最tricky的地方在於,由於兩個鏈表長度不同,到達intersection的時間也不同,所以可能跑完整個鏈表
都不會相遇,所以每個鏈表跑完之後(=none),則指向另一個鏈表的head,繼續跑,這樣每次都在縮短兩個鏈表到達intersection的距離,於是最後在
intersection完美相遇!
 

Leetcode之鏈表(前200道)