Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Task {
- char description[100];
- struct Task* next;
- struct Task* previous;
- };
- struct Task* createTask(char description[]){
- struct Task* newTask = (struct Task*)malloc(sizeof(struct Task));
- strcpy(newTask->description, description);
- newTask->next = NULL;
- newTask->previous = NULL;
- return newTask;
- }
- void addTask(struct Task** head, struct Task* newTask){
- if(*head == NULL) {
- *head = newTask;
- } else {
- struct Task* currentElement = *head;
- while(currentElement->next != NULL){
- currentElement = currentElement->next;
- }
- currentElement->next = newTask;
- newTask->previous = currentElement;
- }
- }
- struct Task* displayFirstTask(struct Task* head){
- if (head == NULL){
- printf("No tasks found!\n");
- } else{
- struct Task* firstTask = head;
- while(firstTask->previous !=NULL){
- firstTask = firstTask-> previous;
- }
- return firstTask;
- }
- }
- void deleteTask(struct Task** head, struct Task* task){
- if (*head == task){
- *head = task->next;
- }
- if(task->previous !=NULL){
- task->previous->next = task->next;
- }
- if(task->next !=NULL){
- task->next->previous = task->previous;
- }
- free(task);
- }
- void displayTasks(struct Task* head){
- struct Task* currentTask = head;
- if(currentTask == NULL){
- printf("No tasks found!\n");
- } else{
- printf("Tasks:\n");
- while(currentTask !=NULL){
- printf("%s\n", currentTask->description);
- currentTask = currentTask->next;
- }
- }
- }
- void freeAllTasks(struct Task** head){
- struct Task* currentTask = *head;
- while(currentTask !=NULL){
- struct Task* next = currentTask->next;
- free(currentTask);
- currentTask = next;
- }
- *head = NULL;
- }
- int main(){
- //initialize queue
- struct Task* tasks = NULL;
- //initialize tasks
- struct Task* firstTask = createTask("Task 1");
- struct Task* secondTask = createTask("Task 2");
- struct Task* thirdTask = createTask("Task 3");
- //add tasks to queue
- addTask(&tasks,firstTask);
- addTask(&tasks->next, secondTask);
- addTask(&tasks->next, thirdTask);
- // print all tasks
- displayTasks(tasks);
- //print first element in fifo
- struct Task* firstTaskInQueue = displayFirstTask(tasks);
- if(firstTask !=NULL){
- printf("First Task: %s\n", firstTaskInQueue -> description);
- }
- //delete specific task
- deleteTask(&tasks,firstTask);
- //show result
- displayTasks(tasks);
- //delete all tasks to save memory
- freeAllTasks(&tasks);
- //show result
- displayTasks(tasks);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement