-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlinkedListFuncs.cpp
More file actions
executable file
·87 lines (63 loc) · 1.74 KB
/
linkedListFuncs.cpp
File metadata and controls
executable file
·87 lines (63 loc) · 1.74 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
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <cassert>
#include "linkedList.h"
#include "linkedListFuncs.h"
LinkedList * arrayToLinkedList(int *a, int size) {
LinkedList * list = new LinkedList;
list->head=NULL;
list->tail=NULL;
for (int i=0; i<size; i++) {
// add array[i] to the list
if ( list->head==NULL) {
list->head = new Node;
list->head->data = a[i]; // (*head).data = a[i];
list->head->next = NULL;
list->tail = list->head;
} else {
list->tail->next = new Node;
list->tail = list->tail->next;
list->tail->next = NULL;
list->tail->data = a[i];
}
}
return list; // return ptr to new list
}
// intToString converts an int to a string
std::string intToString(int i) {
// creates a stream like cout, cerr that writes to a string
std::ostringstream oss;
oss << i;
return oss.str(); // return the string result
}
std::string arrayToString(int a[], int size) {
std::ostringstream oss;
// fencepost problem; first element gets no comma in front
oss << "{";
if (size>0)
oss << intToString(a[0]);
for (int i=1; i<size; i++) {
oss << "," << intToString(a[i]);
}
oss << "}";
return oss.str();
}
// free up every node on this linked list
// nice clean code thanks to @sashavolv2 (on Twitter) #woot
void freeLinkedList(LinkedList * list) {
Node *next;
for (Node *p=list->head; p!=NULL; p=next) {
next = p->next;
delete p;
}
delete list; // returns memory to the heap
}
std::string linkedListToString(LinkedList *list) {
std::string result="";
for (const Node * p=list->head; p!=NULL; p=p->next) {
result += "[" + intToString(p->data) + "]->";
}
result += "null";
return result;
}