LeetCode 141——环形链表

栏目: 数据库 · 发布时间: 7年前

内容简介:定义快慢两个指针,慢指针每次前进一步,快指针每次前进两步,若链表有环,则快慢指针一定会相遇。用 unordered_map 充当散列表的功能,每次将链表的节点指针作为键值存入 map,如果检测到当前节点指针已经存在于 map 中则说明链表有环。获取更多精彩,请关注「seniusen」!
LeetCode 141——环形链表

2. 解答

2.1 方法 1

定义快慢两个指针,慢指针每次前进一步,快指针每次前进两步,若链表有环,则快慢指针一定会相遇。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        
        ListNode *slow = head;
        ListNode *fast = head;
        
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
         return false;
    }
};
复制代码

2.2 方法 2

用 unordered_map 充当散列表的功能,每次将链表的节点指针作为键值存入 map,如果检测到当前节点指针已经存在于 map 中则说明链表有环。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        
        unordered_map<ListNode *, char> nodemap; // 散列表功能
        ListNode *temp = head;
        
        while (temp)
        {
            if (nodemap.count(temp) == 1) return true; // 当前节点已存在于 map 中,则说明有环
            nodemap[temp] = '0';
            temp = temp->next;
        }
        return false;
    }
};
复制代码

获取更多精彩,请关注「seniusen」!

LeetCode 141——环形链表

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Cracking the Coding Interview

Cracking the Coding Interview

Gayle Laakmann McDowell / CareerCup / 2015-7-1 / USD 39.95

Cracking the Coding Interview, 6th Edition is here to help you through this process, teaching you what you need to know and enabling you to perform at your very best. I've coached and interviewed hund......一起来看看 《Cracking the Coding Interview》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试