Skip to content

Instantly share code, notes, and snippets.

@BenMaydan
Last active November 12, 2019 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMaydan/8c90b9b721aaf1c92357d8489d183f89 to your computer and use it in GitHub Desktop.
Save BenMaydan/8c90b9b721aaf1c92357d8489d183f89 to your computer and use it in GitHub Desktop.
Linked list in C++
#include <iostream>
class IntNode {
public:
IntNode* next;
int val;
IntNode(int init) {
val = init;
}
};
class LinkedList {
public:
IntNode* first;
LinkedList(int init) {
first = new IntNode(init);
}
int get(int idx) {
IntNode* node = first;
for (int i = 0; i < idx; i++) {
node = node->next;
}
return node->val;
}
void append(int value) {
IntNode* node = first;
while (node->next) {
node = node->next;
}
node->next = new IntNode(value);
}
void index(int idx, int value) {
IntNode* node = first;
for (int i = 0; i < idx; i++) {
node = node->next;
}
node->val = value;
}
void insert(int idx, int value) {
// Get the node at index idx
IntNode* node = first;
int placeholder;
for (int i = 0; i < idx; i++) {
node = node->next;
}
placeholder = node->val;
node->val = value;
node = node->next;
// Shift all of the nodes' values to the right
while (node->next) {
node->val = placeholder;
node = node->next;
placeholder = node->val;
}
}
void del(int idx) {
if (idx==0) {
IntNode* placeholder = first;
first = first->next;
delete(placeholder);
return;
}
IntNode* pnode;
IntNode* node = first;
for (int i = 0; i < idx; i++) {
if (i == idx-1) pnode = node;
node = node->next;
}
pnode->next = node->next;
delete(node);
}
LinkedList slice(int idx1, int idx2) {
LinkedList n(0);
IntNode* node = first;
for (int i = 0; i < idx2; i++) {
if (i >= idx1) n.append(node->val);
node = node->next;
}
n.del(0);
return n;
}
int length() {
int len = 1;
IntNode* node = first;
while (node->next) {
node = node->next;
len++;
}
return len;
}
void print() {
IntNode* node = first;
int i = 0;
while (node->next) {
std::cout << "Value at index: " << i++ << " = " << node->val << "\n";
node = node->next;
}
}
};
int main() {
LinkedList list(0);
for (int i = 1; i < 10; i++) {
list.append(i);
}
list.index(3, 666);
list.insert(4, 667);
list.del(3);
list.print();
list.slice(0, 3).print();
std::cout << "Length of list = " << list.length() << "\n";
std::cout << "Length of list = " << list.slice(0, 3).length() << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment