打印两个升序链表的公共部分
打印两个升序链表的公共部分
http://www.nowcoder.com/questionTerminal/8943eea40dbb4185b187d80fd050fee9
解题思路
因为是两个升序链表,用两个指针去遍历各自的链表,直到任意指针为空(某一个链表遍历完毕);
如果a_head的值大于b_head的值, 则b_head++(去寻找能等于a链表的节点)
如果a_head的值小于b_head的值, 则a_head++(去寻找能等于b链表的节点)
如果a_head的值等于b_head的值, 则a_head++,b_head++打印公共部分
代码(c++)
void sol(list_node * a_head, list_node * b_head) { //////在下面完成代码 // 如果链表为空 if ( a_head == NULL || b_head == NULL ){ cout << "no recover area!";} list_node* a_pointer = a_head; list_node* b_pointer = b_head; while( a_pointer!=NULL && b_pointer!=NULL ){ if( a_pointer->val == b_pointer->val ){ cout << a_pointer->val << " "; a_pointer = a_pointer->next; b_pointer = b_pointer->next; } else if( a_pointer->val >= b_pointer->val ){ b_pointer = b_pointer->next; } else{ a_pointer = a_pointer->next; } } }