Home > Back-end >  Circular linked list (bosses look error)
Circular linked list (bosses look error)

Time:09-21

/* *
* Definition for singly - linked list.
* struct ListNode {
* int val.
* ListNode * next;
* ListNode (int x) : val (x), next (NULL) {}
*};
*/
The class Solution {
Public:
Bool hasCycle (ListNode * head) {
Unordered_map & lt; Int, int> m;
While (the head)
{
M [head - & gt; val] + +;
If (m/head - & gt; val & gt; 1) return true;
The head=head - & gt; next;
}
return false;
}
};

Why would an error, I put the map key type changed to ListNode * can be used

CodePudding user response:

Given a linked list, whether in the list have ring,

If there is a node list, you can through the continuous track next pointer to arrive again, the list of ring, to show a given list of ring, we use the integer pos to represent the list end connected to the location in the list starting from 0 (index), if pos is 1, is no ring in the list, note: pos passed as a parameter, not only to identify the list of the actual situation,

If the list of rings, the return true, otherwise, returns false,

CodePudding user response:

Can you think again, why ListNode *?
If the list has two nodes at the same val, calculating do not calculate ring? Obviously not, because of the node at the same val, doesn't mean is the same node, such as you have 10 yuan, xiao Ming also have $10, doesn't mean you and xiao Ming is the same person,
But if the list has two nodes at the same address, calculating do not calculate ring? Clearly, because the node address is the same, is on behalf of the same node, such as memory address you live 1, xiao Ming living memory address 1, then can show you and little star the same person (because of the same piece of computer memory can keep the same thing, you and xiao Ming is stored in the same block of memory, you is xiao Ming),
  • Related