力扣题:链表中的双指针技巧-10.19

力扣题-10.19

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:141. 环形链表

解题思想:将遍历过的链表进行记录即可

在这里插入图片描述

# 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
        """
        if head == None:
            return False
        node_list = []
        temp = head
        while temp.next!=None:
            if temp in node_list:
                return True
            else:
                node_list.append(temp)
            temp = temp.next
        return False
/**
 * 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) {
        unordered_set<ListNode*> node_list;
        if(head==nullptr){
            return false;
        }
        ListNode * temp = head;
        while(temp->next!=nullptr){
            if(node_list.count(temp)){
                return true;
            }
            else{
                node_list.insert(temp);
            }
            temp = temp->next;
        }
        return false;
    }
};

力扣题2:142. 环形链表 II

解题思想:同上一题一样,只是返回的结果不同

在这里插入图片描述

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

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return 
        node_list = []
        temp = head
        while temp.next!=None:
            if temp in node_list:
                return temp
            else:
                node_list.append(temp)
            temp = temp.next
        return 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> node_list;
        if(head==nullptr){
            return NULL;
        }
        ListNode * temp = head;
        while(temp->next!=nullptr){
            if(node_list.count(temp)){
                return temp;
            }
            else{
                node_list.insert(temp);
            }
            temp = temp->next;
        }
        return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值