Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdexcept>
- using namespace std;
- class SinglyLinkedList {
- private:
- class Node {
- public:
- Node* next;
- char data;
- Node(char data, Node* next) {
- this->data = data;
- this->next = next;
- }
- };
- Node* head;
- int length;
- public:
- SinglyLinkedList() {
- this->head = nullptr;
- this->length = 0;
- }
- ~SinglyLinkedList() {
- Node* no = this->head;
- while (no != nullptr) {
- Node* noNext = no->next;
- delete no; //eyðum hnút
- no = noNext; //sækjum næsta
- }
- cout << "Kallað hefur verið á eyðinn fyrir listann" << endl;
- }
- int size() { return this->length; }
- void display() {
- for (Node* node = this->head; node != nullptr; node = node->next) {
- cout << node->data << " -> ";
- }
- cout << "Ø" << endl;
- }
- void prepend(char c) {
- Node* pre = new Node(c, this->head); //ný hnútur sem vísar á haus
- this->head = pre; //þessi punktur verður hausinn
- this->length++;
- }
- char operator[](int n) {
- if (n < this->length) {
- Node* no = this->head;
- for (int i=0; i<n; i++) { //flökkum n sinnum um listann
- no = no->next;
- }
- return no->data; //skilum gögnunum sem n-ti hnúturinn inniheldur
- } else {
- //ef n er útfyrir lengd listans (semsagt jafntog eða stærri):
- throw out_of_range("Index out of range");
- }
- }
- };
- int main() {
- // Skilgreining lista sem inniheldur tákn
- SinglyLinkedList list;
- list.prepend('G');
- list.prepend('3');
- list.prepend('0');
- list.prepend('2');
- list.prepend('L');
- list.prepend('O');
- list.prepend('T');
- list.display();
- cout << "Stak 0 í listanum er " << list[0] << endl;
- cout << "Stak 3 í listanum er " << list[3] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment