Files
aisd/Lab2/list/list.cpp
T

56 lines
1.0 KiB
C++

#include "list.h"
#include <sys/types.h>
List *insert(List *head, int value) {
if (head == nullptr) {
List *node = new List();
node->data = value;
node->next = nullptr;
return node;
}
if (head->data > value) {
List *newHead = new List();
newHead->data = value;
newHead->next = head;
head = newHead;
} else {
List *tmp = head;
while (tmp->next != nullptr && tmp->data < value) {
tmp = tmp->next;
}
List *tail = new List();
tail->data = value;
// Set the pointer to the next, we don't know if its at the end or not
tail->next = tmp->next;
tmp->next = tail;
}
return head;
}
List *search(List *list, int value) {
List *ptr = list;
while (ptr != nullptr && ptr->data != value) {
ptr = ptr->next;
}
if (ptr->data == value) {
return ptr;
}
return nullptr;
}
// Remove the first element
List *remove(List *head) {
if (head == nullptr) {
return nullptr;
}
List *newHead = head->next;
delete head;
return newHead;
}