- 使用方式(head是头指针)
if(head == nullptr) return head;
Node* slow = head->next;
Node* fast = head->next;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
明确快慢指针最后到达的位置:
如果是偶数,如1 2 3 4 5 6,那么slow到达的是4,fast到达的是null;
如果是奇数,如1 2 3 4 5,那么slow到达的是3,fast到达的是5;
题一:链表 检查是够有环 以及环的长度
思路: 快指针、慢指针;如果有环,则快指针一定会与慢指针相遇;且环的初始结点:从头结点一步一步走和从相遇的点一步步走最后相遇的地方。
Node* check(Node* head){
if(head == nullptr || head->next == nullptr||head->next->next == nullptr){
return nullptr;
}
Node* fast= head->next->next;
Node* slow = head->next;
while(fast!=slow){
if(fast->next!=nullptr && fast->next->next != nullptr){
fast = fast->next->next;
slow = slow->next;
}else{
return nullptr;
}
}
fast = head;
while(fast!=slow){
fast = fast->next;
slow = slow ->next;
}
return slow;
}
int length(Node* head){
Node* myhead =check(head)
if(!myhead) return 0;
int cnt = 1;
Node* p= myhead->next;
while(p!=myhead){
p = p ->next;
cnt++;
}
return cnt;
}
题二:带有空格的数组,进行翻转,并去除空格
思路:把翻转之后的字符拎到两边
string s = "s e p o";
int len = s.size();
int start = 0, end = len -1;
int i = 0 , j = len-1;
while( start < end ){
if(s[start] == ' '){
start++;
continue;
}
if(s[end] == ' '){
end--;
continue;
}
char temp = s[start];
s[start] = s[end];
s[end] = temp;
s[i++] = s[start];
s[j--] = s[end];
start++;
end--;
}
string res = s.substr(0,i)+s.substr(j+1,len-j-1);
return res;