-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked_lists.h
95 lines (76 loc) · 1.93 KB
/
Linked_lists.h
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
93
94
95
#pragma once
#include <iostream>
#include <string>
#include "LinkedList.h"
/********************************************************************
insertOrdered
********************************************************************/
template <typename T>
void LinkedList<T>::insertOrdered(const T& newData) {
// Make your new node on the heap
Node *nn = new Node(newData);
// Base case, empty list
if (!head_){
tail_ = nn;
head_ = nn;
}
// Inserted number is greater than or equal to current entries
else if (newData >= tail_ -> data){
tail_ -> next = nn;
nn -> prev = tail_;
tail_ = nn;
}
// Inserted number is less than or equal to current entries
else if (newData <= head_ -> data){
head_ -> prev = nn;
nn -> next = head_;
head_ = nn;
}
// Inserted number is within the tail and head range
else{
Node *cn = head_ -> next;
while (newData > cn -> data){
cn = cn -> next;
}
// Found the spot to insert number
nn -> next = cn;
nn -> prev = cn -> prev;
cn -> prev -> next = nn;
cn -> prev = nn;
cn = nn;
}
size_ += 1;
return;
}
/********************************************************************
Exercise 2: Linear-time Merge
********************************************************************/
template <typename T>
LinkedList<T> LinkedList<T>::merge(const LinkedList<T>& other) const {
LinkedList<T> left = *this;
LinkedList<T> right = other;
LinkedList<T> merged;
while(!right.empty() && !left.empty()){
if(right.front() <= left.front()){
merged.pushBack(right.front());
right.popFront();
}
else{
merged.pushBack(left.front());
left.popFront();
}
}
if(right.empty()){
while(!left.empty()){
merged.pushBack(left.front());
left.popFront();
}
}
else{
while(!right.empty()){
merged.pushBack(right.front());
right.popFront();
}
}
return merged;
}