Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active April 25, 2020 02:33
Show Gist options
  • Save nezarfadle/ef62871987d87b8e78edbc408d414b9a to your computer and use it in GitHub Desktop.
Save nezarfadle/ef62871987d87b8e78edbc408d414b9a to your computer and use it in GitHub Desktop.
#pragma once

using namespace std;

class Node
{

public:
	
	int data;
	Node *next;

	bool isEndOfList()
	{
		if (this == nullptr)
		{
			return true;
		}

		return false;
	}

	bool hasNext()
	{
		
		if (this == nullptr || this->next == nullptr)
		{
			return false;
		}

		return true;
	}

	void dispose()
	{
		delete this;
	}

	static Node* create(int data)
	{
		Node* n = new Node();
		n->data = data;
		n->next = nullptr;
		return n;
	}

};

class IntLinkedList
{

private:

	Node* head;
	Node* tail;

public:

	Node* current;

	IntLinkedList()
	{
		head = tail = nullptr;
	}


	IntLinkedList* insertRange(int from, int to)
	{
		for (int i = from; i <= to; i++)
		{
			this->insert(i);
		}

		return this;
	}

	IntLinkedList* insert(int data)
	{
		
		if (head == nullptr)
		{
			head = tail = Node::create(data);
			return this;
		}

		Node *tmp = Node::create(data);
		tail->next = tmp;
		tail = tmp;

		return this;
	}

	IntLinkedList* inserAt(int index, int data)
	{
		throw "Function not yet implemented";
	}

	IntLinkedList* remove(int index)
	{
		
		if (index <= 0) return this;

		int counter = 1;
		Node* tmp = head;
		
		// Remove the head and return
		if (index - 1 == 0)
		{
			head = tmp->next;
			tmp->dispose();
			return this;
		}

		// Loop at least once
		do
		{

			tmp = tmp->next;
			if ( !tmp->hasNext() ) return this;

			counter++;

		} while (counter < index - 1);


		Node* toBeRemoved = tmp->next;
		tmp->next = toBeRemoved->next;
		delete toBeRemoved;

		if (tmp->next == nullptr)
		{
			tail = tmp;
		}

		return this;
	}

	// Take a callback function and iterate over the Linkedlist Items
	IntLinkedList* travers( void(fn)(Node* n) )
	{
		
		Node *list = head;

		while ( !list->isEndOfList() )
		{
			fn(list);
			list = list->next;	
		}

		return this;

	}
};
// DSApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "IntLinkedList.h"

int main()
{

	IntLinkedList* list = new IntLinkedList();
	
	list->insertRange(1, 10)
	    ->remove(1)
	    ->travers( [](Node* n) {
		std::cout << n->data << endl;
	    });
	
	std::getchar();
	return 0;

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment