Created
April 4, 2023 08:49
-
-
Save muaddib1971/a15fb377e7465728c8f3256348989a3c to your computer and use it in GitHub Desktop.
c++ linked list
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 "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(); | |
} |
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
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