- 查找链表的中点
LinkNode* middle(LinkNode* head) { LinkNode *fast = head; //快慢指针起点相同 LinkNode *slow = head; //使用快慢指针 while(fast && fast->next) { slow = slow->next; fast = fast->next->next; } if(fast) //根据结束条件 判断 中间节点的位置 return slow; else return slow->next; }
2. 判断链表有环
bool isCircle(LinkNode* head) { LinkNode *fast = head; LinkNode *slow = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if(slow == fast) return true; } return false; }
3. 计算环的起点, 链表长度, 还的环的长度
void Circle(LinkNode * head) { int slowStep; //slow 走过的步数 int pos; //从链表开始记录的步数 LinkNode *slow = head; LinkNode *fast = head; slowStep = 1; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; slowStep++; if(slow == fast) break; } pos = 1; LinkNode *p = head; while(p != slow) //同时从第一个相交的点 和 起点开始遍历 { p = p->next; slow = slow->next; pos++; } /* 环的起点 p; 链表的长度 slowStep+pos-1; 环的长度 slowSteps; */ return; }
//方法2 根据hash查找环的起点 LinkNode * CircleStart(LinkNode* head) { unoedered_set<LinkNode*> hash; LinkNode* p = head; while(p) { if(hash.find(p) == hash.end()) { hash.insert(p); }else break; p = p->next; } return p; }
//方法2 计算环的长度 int CircleLength(LinkNode* head) { LinkNode *fast = head; LinkNode *slow = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if(slow == fast) break; } int lenght = 1; while(true) { slow = slow->next; fast = fast->next->next; length++; if(slow == fast) break; //再一次相遇时 slow 走了一圈,fast走了两圈。 } return length; }
时间: 2024-10-10 15:18:27