Last active
September 17, 2021 15:28
-
-
Save zhhailon/057988edb70491cce05da98d3fc882b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class IntNode { | |
public: | |
int item; | |
IntNode *next; | |
IntNode(int i, IntNode *n) { | |
item = i; | |
next = n; | |
} | |
}; | |
class SLList { | |
private: | |
/** Pointer pointing to the first element in list. */ | |
// IntNode *first; | |
/** Pointer pointing to the sentinel node. */ | |
IntNode *sentinel; | |
/** Stores the current size of the list. */ | |
int count; | |
/** Helper method that returns size recursively. */ | |
// int size(IntNode *p) const { | |
// if (p->next == nullptr) | |
// return 1; | |
// return 1 + size(p->next); | |
// } | |
public: | |
/** Construct a new SLList object. */ | |
SLList() { | |
// first = nullptr; | |
sentinel = new IntNode(63, nullptr); | |
count = 0; | |
} | |
/** Construct a new SLList object with element x. */ | |
SLList(int x) { | |
// first = new IntNode(x, nullptr); | |
sentinel = new IntNode(63, nullptr); | |
count = 0; | |
addFirst(x); | |
} | |
/** Add x at the beginning of the list. */ | |
void addFirst(int x) { | |
count += 1; | |
// first = new IntNode(x, first); | |
sentinel->next = new IntNode(x, sentinel->next); | |
} | |
/** Return the first element. */ | |
int &getFirst() { | |
// return first->item; | |
return sentinel->next->item; | |
} | |
/** Return the number of elements in list. */ | |
int size() const { | |
return count; | |
// return size(first); | |
} | |
/** Append the list with x. */ | |
void addLast(int x) { | |
count += 1; | |
// if (first == NULL) { | |
// first = new IntNode(x, NULL); | |
// return; | |
// } | |
// IntNode *p = first; | |
IntNode *p = sentinel; | |
while (p->next != nullptr) { | |
p = p->next; | |
} | |
p->next = new IntNode(x, nullptr); | |
} | |
}; | |
int main() { | |
SLList L(10); | |
L.addFirst(5); | |
L.addLast(15); | |
std::cout << L.size() << std::endl; | |
std::cout << L.getFirst() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment