Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Created April 4, 2023 08:49
Show Gist options
  • Save muaddib1971/a15fb377e7465728c8f3256348989a3c to your computer and use it in GitHub Desktop.
Save muaddib1971/a15fb377e7465728c8f3256348989a3c to your computer and use it in GitHub Desktop.
c++ linked list
#include "IntList.h"
#include <climits>
Node::Node(int _data) : next(nullptr), data(_data) {}
void Node::setNext(Node* next) { this->next = next; }
Node* Node::getNext() { return next; }
int Node::getData() { return data; }
LinkedList::LinkedList() : head(nullptr), size(0) {}
void LinkedList::add(int data) {
Node* current, *prev = nullptr;
current = head;
while (current) {
prev = current;
current = current->getNext();
}
prev->setNext(new Node(data));
size++;
}
int LinkedList::get(int offset) {
// max value offset?
if (offset < 0 || offset >= size) {
return INT_MIN;
}
Node* current = head;
int count = 0;
while (count < offset) {
++count;
current = current->getNext();
}
return current->getData();
}
class Node {
public:
Node(int _data);
void setNext(Node* next);
Node* getNext();
int getData();
private:
Node* next;
int data;
};
class LinkedList {
public:
LinkedList();
void add(int data);
int get(int offset);
private:
Node* head;
int size;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment