利用两个指针向后走,只要相遇就是一个环,遇不上就不是一个环
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
if(head->next == NULL) return false;
if(head == head->next) return true;
ListNode *slow = head;
ListNode *fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
两数相加
新建一片内存空间之后加起来,存入,进位存入int中
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *OCC = new ListNode(0);
ListNode *count1 = l1,*count2 = l2;
ListNode *tmp = OCC;
int out = 0;
while(count1 != nullptr && count2 != nullptr) {
tmp->next = new ListNode((count1->val + count2->val + out) % 10);
tmp = tmp->next;
out = (count1->val + count2->val + out) / 10;
count1 = count1->next;
count2 = count2->next;
}
while(count1 != nullptr) {
tmp->next = new ListNode((count1->val + out) % 10);
tmp = tmp->next;
out = (count1->val + out) / 10;
count1 = count1->next;
}
while(count2 != nullptr) {
tmp->next = new ListNode((count2->val + out) % 10);
tmp = tmp->next;
out = (count2->val + out) / 10;
count2 = count2->next;
}
if(out != 0) tmp->next = new ListNode(out);
return OCC->next;
}