-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectors.cpp
More file actions
116 lines (106 loc) · 2.01 KB
/
Copy pathvectors.cpp
File metadata and controls
116 lines (106 loc) · 2.01 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
// Struct consisting of vector attributes.
struct Vector
{
int data;
struct Vector *next;
};
struct Vector *head = NULL;
// Adds userData to the front of the vector by creating a new node
void push_front(int userData)
{
struct Vector *new_node = (struct Vector *)malloc(sizeof(struct Vector));
new_node->data = userData;
new_node->next = head;
head = new_node;
}
// Removes the first item of the vector
void remove()
{
struct Vector *ptr;
ptr = head;
head = head->next;
free(ptr);
}
// Removes from the given index
int removeFrom(int index)
{
struct Vector *ptr, *initialPos, *newPtr;
int initialIndex = 0;
initialPos = head;
if (index == 0)
{
ptr = head;
head = head->next;
free(ptr);
return 0;
}
else if (index == 1)
{
ptr = head->next;
head->next = ptr->next;
free(ptr);
return 0;
}
while (index - initialIndex != 1)
{
initialIndex++;
head = head->next;
}
ptr = head->next;
head->next = ptr->next;
head = initialPos;
free(ptr);
return 0;
}
// Prints the item from the given index
void printFrom(int index)
{
struct Vector *ptr;
ptr = head;
if (index == 0)
{
ptr = head;
}
else if (index == 1)
{
ptr = head->next;
}
else
{
while (index != 0)
{
index = index - 1;
ptr = ptr->next;
}
}
cout << ptr->data << "\n";
}
// Displays all the items in the vector
void displayAll()
{
struct Vector *ptr;
ptr = head;
while (ptr != NULL)
{
std::cout << ptr->data << " ";
ptr = ptr->next;
}
cout << std::endl;
}
int main()
{
// Test cases //
// push_front(5);
// push_front(4);
// push_front(6);
// push_front(23);
// push_front(8);
// push_front(34);
// push_front(45);
// printFrom(5);
// displayAll();
}