Leetcode之链表(前200道)

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完美相遇!
 
时间: 2024-08-01 07:19:42

Leetcode之链表(前200道)的相关文章

200道历年逻辑推理真题详解

200道历年逻辑推理真题详解 01.粮食可以在收割前在期货市场进行交易.如果预测谷物产量不足,谷物期货价格就会上升:如果预测谷物丰收,谷物期货价格就会下降.今天早上,气象学家们预测从明天开始谷物产区里会有非常需要的降雨.因为充分的潮湿对目前谷物的存活非常重要,所以今天的谷物期货价格会大幅下降. 下面哪个,如果正确,最严重地削弱了以上的观点? A.在关键的授粉阶段没有接受足够潮湿的谷物不会取得丰收. B.本季度谷物期货价格的波动比上季度更加剧烈. C.气象学家们预测的明天的降雨估计很可能会延伸到谷

16.有一分数序列 1/2,2/3,3/5,5/8,8/13,13/21,…求出这个序列的前200 项之和

使用向量: #include<iostream>#include<vector>using namespace std;int FenShu(int); int main(){    double sum=0,sum1=0;    for(int i=2;i<=200;i++)    {        sum1+=FenShu(i);    }    sum=sum1+0.5;    cout<<sum<<endl;    return 0;} int

[LeetCode系列]链表环探测问题II

给定一个链表头, 探测其是否有环, 如果没有返回NULL, 如果有返回环开始的位置. 环开始的位置定义为被两个指针指向的位置. 算法描述: 1. 快慢指针遍历, 如果到头说明无环返回NULL, 如果相遇说明有环, 进入2. 2. 慢指针回到起点, 快慢指针每次移动一格直到相遇, 返回快指针/慢指针. 代码: 1 class Solution { 2 public: 3 ListNode *detectCycle(ListNode *head) { 4 if (!head || !head->ne

巧妙使用SQL Server编辑前200行功能

在SQL Server 2005/2008/2008 R2中,我们可以使用SQL Server自带的编辑前200行功能,使用这个功能的本意是简化Update 的使用,让开发人员.DBA和不懂T-SQL的一些人能够通过可视化界面来直接修改数据库里的数据. 在使用编辑前200行功能的时候,编辑前200行数据,简便是简便了,但是简便了以后更想直接在可视化的页面里直接编辑想要编辑的数据,而不是打开编辑界面后自动读出来的200条,自动读出来的200条顺序杂乱,本来是一个很好用的强大功能,显得有些鸡肋. 在

InfoQ:开放物联网大会启动筹备,(前200名)免费报名参与

开放物联网大会2014,12月18日,北京国际会议中心, 现可免费报名参与(前200名,优惠码 OIOT-KYZG-VIP 即时获得免费电子票), 可惜是周四,不知道大家有没有兴趣呢? 报名网址:http://www.openiotcon.com/index.html (注:优惠码来自开源中国)

【算法题 14 LeetCode 147 链表的插入排序】

算法题 14 LeetCode 147 链表的插入排序: 解题代码: # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode

LeetCode 单链表专题 (一)

目录 LeetCode 单链表专题 <c++> \([2]\) Add Two Numbers \([92]\) Reverse Linked List II \([86]\) Partition List \([82]\) Remove Duplicates from Sorted List II \([61]\) Rotate List \([19]\) Remove Nth Node From End of List LeetCode 单链表专题 <c++> \([2]\)

LeetCode 206 链表 Reverse Linked List

LeetCode 206 链表 Reverse Linked List Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement

LeetCode 142 链表 Linked List Cycle II

LeetCode 142 链表 Linked List Cycle II LeetCode Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexe