This repository was archived by the owner on May 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortedLinkedList.cpp
128 lines (112 loc) · 2.71 KB
/
SortedLinkedList.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* File: SortedLinkedList.cpp
* Course: CS216-00x
* Project: Project 2
* Purpose: the implementation of member functions for the Node class and SortedLinkedList class.
*** DO NOT CHANGE THIS FILE ***
*
*/
#include <cstdlib>
#include <iostream>
#include "SortedLinkedList.h"
using namespace std;
// Implementation for the member functions of the Node class
Node::Node()
{
next = NULL;
}
Node::Node(Card value)
{
data = value;
next = NULL;
}
// Implementation for the member functions of the SortedLinkedList class
//default constructor
SortedLinkedList::SortedLinkedList()
{
head = NULL;
}
// insert a new node, which is a Card object to the list
// so that the nodes are in non-decreasing order of card values defined by poker game
// To maintain this order, the list needs to use insert() ONLY to add new node
void SortedLinkedList::insert(Card newcard)
{
Node* newnode = new Node(newcard);
Node* pre = NULL;
Node* current = head;
while (current!= NULL && newcard.compareTo(current->data) < 0)
{
pre = current;
current = current->next;
}
if (current == head)
{
newnode->next = head;
head = newnode;
}
else
{
pre->next = newnode;
newnode->next = current;
}
}
// remove the front node from the list
void SortedLinkedList::pop_front()
{
if (size() == 0)
cout << "Cannot remove from an empty list." << endl;
else
{
Node* tmp = head;
head = head->next;
delete tmp;
}
}
// return how many nodes in the list
int SortedLinkedList::size() const
{
int count = 0;
Node* current = head;
while (current != NULL)
{
current = current->next;
count++;
}
return count;
}
// return true if the list is empty
// otherwise return false
bool SortedLinkedList::isEmpty() const
{
return (size()==0);
}
// return a vector of nodes
// which stores the nodes from the sorted list.
// provide flexible way to access the nodes in the list
vector<Card> SortedLinkedList::access() const
{
vector<Card> nodes_in_list;
Node* current = head;
while (current != NULL)
{
nodes_in_list.push_back(current->data);
current = current->next;
}
return nodes_in_list;
}
// display the nodes in the list from the front to the tail
void SortedLinkedList::print() const
{
vector<Card> nodes = access();
for (int i = 0; i < nodes.size(); i++)
{
nodes[i].print();
cout << "\t";
}
cout << endl;
}
//destructor
SortedLinkedList::~SortedLinkedList()
{
while (!isEmpty())
pop_front();
}