数据结构与算法(二)链表,如何高效实现与优化?

2026-04-16 20:072阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计208个文字,预计阅读时间需要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) { + set address; + ListNode* current=head; + while (current !=NULL) { + if (address.find(current) !=address.end()) { + return true; + } + address.insert(current); + current=current->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) { set<ListNode *> address; ListNode* pos=head; while(true){ if(pos==NULL){ return false; } if(address.count(pos)==1){ return true; }else { address.insert(pos); } pos=pos->next; } return true; } };

  

要点:

c++ STL 函数 Set关联容器支持高效的关键字查找和访问

set.insert(1);

set.count(1)

数据结构与算法(二)链表,如何高效实现与优化?

count()用来查找set中某个某个键值出现的次数。这个函数在set并不是很实用,因为一个键值在set只可能出现0或1次,这样就变成了判断某一键值是否在set出现过了。

set底层实现方式为RB树(即红黑树)

本文共计208个文字,预计阅读时间需要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) { + set address; + ListNode* current=head; + while (current !=NULL) { + if (address.find(current) !=address.end()) { + return true; + } + address.insert(current); + current=current->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) { set<ListNode *> address; ListNode* pos=head; while(true){ if(pos==NULL){ return false; } if(address.count(pos)==1){ return true; }else { address.insert(pos); } pos=pos->next; } return true; } };

  

要点:

c++ STL 函数 Set关联容器支持高效的关键字查找和访问

set.insert(1);

set.count(1)

数据结构与算法(二)链表,如何高效实现与优化?

count()用来查找set中某个某个键值出现的次数。这个函数在set并不是很实用,因为一个键值在set只可能出现0或1次,这样就变成了判断某一键值是否在set出现过了。

set底层实现方式为RB树(即红黑树)