面试经典150题 - 链表
class Solution {
public : bool hasCycle ( ListNode * head) { ListNode* slow = head, * fast = head; while ( fast != nullptr && fast-> next != nullptr ) { slow = slow-> next; fast = fast-> next-> next; if ( slow == fast) { return true ; } } return false ; }
} ;
class Solution {
public : ListNode * detectCycle ( ListNode * head) { ListNode* slow = head, * fast = head; while ( fast != nullptr && fast-> next != nullptr ) { slow = slow-> next; fast = fast-> next-> next; if ( slow == fast) { slow = head; while ( slow != fast) { slow = slow-> next; fast = fast-> next; } return slow; } } return nullptr ; }
} ;
class Solution {
public : ListNode* addTwoNumbers ( ListNode* l1, ListNode* l2) { ListNode* dummy_head = new ListNode ( 0 ) ; ListNode* cur = dummy_head, * cur_1 = l1, * cur_2 = l2; int sum = 0 , carry = 0 ; while ( cur_1 || cur_2 || carry != 0 ) { sum = 0 ; if ( cur_1) { sum += cur_1-> val; cur_1 = cur_1-> next; } if ( cur_2) { sum += cur_2-> val; cur_2 = cur_2-> next; } sum += carry; carry = sum / 10 ; cur-> next = new ListNode ( sum % 10 ) ; cur = cur-> next; } ListNode* head = dummy_head-> next; delete dummy_head; dummy_head = nullptr ; return head; }
} ;
class Solution {
public : ListNode* mergeTwoLists ( ListNode* node_1, ListNode* node_2) { ListNode* dummy_head = new ListNode ( ) ; ListNode* cur = dummy_head; while ( node_1 != nullptr && node_2 != nullptr ) { if ( node_1-> val < node_2-> val) { cur-> next = node_1; node_1 = node_1-> next; } else { cur-> next = node_2; node_2 = node_2-> next; } cur = cur-> next; } cur-> next = node_1 ? node_1 : node_2; ListNode* head = dummy_head-> next; delete dummy_head; dummy_head = nullptr ; return head; }
} ;
class Solution {
public : Node* copyRandomList ( Node* head) { unordered_map< Node* , Node* > copy_hash; Node* cur = head; while ( cur) { copy_hash[ cur] = new Node ( cur-> val) ; cur = cur-> next; } cur = head; while ( cur) { copy_hash[ cur] -> random = copy_hash[ cur-> random] ; copy_hash[ cur] -> next = copy_hash[ cur-> next] ; cur = cur-> next; } return copy_hash[ head] ; }
} ;