题目描述
【题目】给定两个有序链表的头指针head1和head2,打印两个链表的公共部分
【要求】如果两个链表的长度之和为N,时间复杂度要求O(N),额外空间复杂度为O(1)
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
void printCommon(ListNode* head1, ListNode *head2) {
}
};
题目解析
因为是有序链表,所以从两个链表的头结点开始判断:
- 如果head1的值小于head2,那么head1下移
- 如果head2的值小于head1,那么head2下移
- 如果两者相同,那么打印这个值,然后head1和head2均下移
- head1或者head2中只要有一个移动到null,那么整个过程停止
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
void printCommon(ListNode* head1, ListNode *head2) {
ListNode *curr1 = head1, *curr2 = head2;
while (curr1 != nullptr && curr2 != nullptr){
if(curr1 == curr2){
printf("%d\t", curr1->val);
curr1 = curr1->next;
curr2 = curr2->next;
}else if(curr1->val < curr2->val){
curr1 = curr1->next;
}else{
curr2 = curr2->next;
}
}
}
};