-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtarget_pair_sum.cpp
More file actions
92 lines (80 loc) · 1.8 KB
/
target_pair_sum.cpp
File metadata and controls
92 lines (80 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
*/
#include <iostream>
using namespace std;
#include <vector>
#include <limits.h>
class node{
public:
int value;
node *prev;
node *next;
// construtor
node(int data){
value = data;
prev = nullptr;
next = nullptr;
}
};
class DoublyLinkedList{
public:
node *head;
node *tail;
DoublyLinkedList(){
head = nullptr;
tail = nullptr;
}
void display(){
node *temp = head;
while (temp != nullptr){
cout << temp->value << " ";
temp = temp->next;
}
cout << endl;
}
void insertAtEnd(int value){
node *new_node = new node(value);
// check if linked list is empty
if (head == nullptr){
head = new_node;
tail = new_node;
return;
}
// if linked list is not empty
tail->next = new_node;
new_node->prev = tail;
tail = new_node;
return;
}
};
vector<int>pairSumDLL(node *&head, node *&tail, int x){
vector<int>ans(2,-1);
while(head != tail){
int sum = head -> value + tail -> value;
if(sum == x){
ans[0] = head -> value;
ans[1] = tail -> value;
return ans;
}
else if(sum > x){ // i need smaller values, i will move by tail back
tail = tail -> prev;
}
else{ // i need bigger value, i will move forward
head = head -> next;
}
}
return ans;
}
int main(){
DoublyLinkedList dll;
cout << "Inserted Linked List: ";
dll.insertAtEnd(2);
dll.insertAtEnd(5);
dll.insertAtEnd(6);
dll.insertAtEnd(8);
dll.insertAtEnd(10);
dll.display();
vector<int>ans = pairSumDLL(dll.head, dll.tail, 11);
cout<<ans[0]<<endl<<ans[1];
return 0;
}