Skip to content

Commit

Permalink
Merge pull request #4 from realmarkoprifti/final-oop-approach
Browse files Browse the repository at this point in the history
Implemented more features
  • Loading branch information
realmarkoprifti authored Oct 4, 2023
2 parents f57222f + 65fa460 commit 4a0c3e9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 48 deletions.
97 changes: 57 additions & 40 deletions src/linkedlist.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ LinkedList::LinkedList(int* numArr, int arrSize, int type)
"Invalid type of linked list. 1 -> Singly linked list, 2 -> Doubly linked list"
);
}

listType = type;
}


Expand Down Expand Up @@ -121,57 +123,58 @@ void LinkedList::insert(int val)

void LinkedList::delNode(int val)
{

ListNode* ptr = NULL;
ListNode* prev = head;

for (ptr = head; ptr != NULL; ptr = ptr->next)
for (ListNode* ptr = head; ptr != NULL; ptr = ptr->next)
{
if (head == ptr && ptr->val == val)
if (ptr->val == val)
{
std::cout << "Deleting head node..." << std::endl;
ListNode* tmp = ptr->next;
delete ptr;
head = tmp;

if (head != NULL)
if (ptr == head)
{
head->prev = NULL;
}
}

else if (tail == ptr && ptr->val == val)
{
delete ptr;
tail = prev;
prev->next = NULL;
ptr = prev;

}
if (listType == 1)
{
ListNode* tmp = ptr->next;
delete ptr;
head = tmp;
}

else if (ptr->val == val)
{
else
{
ListNode* tmp = ptr->next;
tmp->prev = NULL;
delete ptr;
head = tmp;
}
}

// Check if the list is doubly linked
if (ptr->prev != NULL)
else if (ptr == tail)
{
prev->next = ptr->next;
ptr->next->prev = prev;
prev->next = NULL;
delete ptr;
}

// Else it's singly linked
else
tail = prev;
}

else
{
prev->next = ptr->next;
delete ptr;
}
}
if (listType == 1)
{
ListNode* tmp = ptr->next;
prev->next = tmp;
delete ptr;

// Just for the aesthetics
else
{
continue;
return;
}

else
{
ListNode* tmp = ptr->next;
prev->next = tmp;
tmp->prev = prev;

delete ptr;
return;
}
}
}

prev = ptr;
Expand Down Expand Up @@ -230,4 +233,18 @@ void LinkedList::print()
{
std::cout << ptr->val << std::endl;
}
}


ListNode* LinkedList::lsearch(int val)
{
for (ListNode* ptr = head; ptr != NULL; ptr = ptr->next)
{
if (ptr->val == val)
{
return ptr;
}
}

return NULL;
}
18 changes: 10 additions & 8 deletions src/linkedlist.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ struct ListNode
class LinkedList
{
private:
struct ListNode
{
int val;
ListNode* prev;
ListNode* next;
};
//struct ListNode
//{
// int val;
// ListNode* prev;
// ListNode* next;
//};
ListNode* head;
ListNode* tail;
int listType;


bool isSorted();

Expand All @@ -36,9 +38,9 @@ class LinkedList
void delNode(int val);
int length();
void sort();
ListNode* search(int val);
void print();
ListNode* lsearch(int val);

};


#endif

0 comments on commit 4a0c3e9

Please sign in to comment.