Hi so I had a quiz on writing a linked list in C and I don\'t think it went that
ID: 3747939 • Letter: H
Question
Hi so I had a quiz on writing a linked list in C and I don't think it went that well. I was given the header file below and then had to implement in the C file ll_init, ll_add, and ll_remove. If someone would help me to implement these 3 methods it would help me a lot when implementing them for the upcoming test. Thanks!
______________________________________________________________________________
Implement the methods with the header file below.
#include "linkedlist.h"
void ll_init(struct linkedList* list)
{
}
bool ll_add(struct linkedList* list, const void* object, uint32_t size)
{
}
bool ll_remove(struct linkedList* list, uint32_t index)
{
}
__________________________________________________________________________
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include
#include
struct listNode {
void* data;
uint32_t dataSize;
struct listNode* nextNode;
struct listNode* prevNode;
};
struct linkedList
{
struct listNode* head;
struct listNode* tail;
uint32_t size;
};
struct linkedListIterator
{
struct listNode* current;
};
void ll_init(struct linkedList* list);
bool ll_add(struct linkedList* list, const void* object, uint32_t size);
bool ll_addIndex(struct linkedList* list, const void* object, uint32_t size, uint32_t index);
bool ll_remove(struct linkedList* list, uint32_t index);
void* ll_get(struct linkedList* list, uint32_t index);
void ll_clear(struct linkedList* list);
uint32_t ll_size(struct linkedList* list);
struct linkedListIterator* ll_getIterator(struct linkedList* list);
bool ll_hasNext(struct linkedListIterator* iter);
void* ll_next(struct linkedListIterator* iter);
#endif
Explanation / Answer
call these functions from main and pass the parameters properly.
void ll_init(struct linkedList* list)
{
list->head = NULL;
list->tail = NULL;
list->size = 0;
}
bool ll_add(struct linkedList* list, const void* object, uint32_t size)
{
struct listNode *newNode = (struct listNode*)malloc(sizeof(struct listNode));
newNode->data = object;
newNode->dataSize = size;
newNode->prevNode = NULL;
newNode->nextNode=NULL;
if(list->head == NULL)
{
list->head = newNode;
list->tail = newNode;
}
else
{
newNode->nextNode=list->head;
list->head->prevNode = newNode;
list->head=newNode;
}
}
bool ll_remove(struct linkedList* list, uint32_t index)
{
if(!list->head || !list->tail)
return false;
struct listNode *temp=list->head;
for(int i=1;temp!=NULL && i<index;i++)
temp = temp->nextNode;
if(temp == NULL)
return false;
if(list->head == temp)
{
list->head == temp->nextNode;
if(temp->nextNode != NULL)
list->head->prevNode = NULL;
}
else
{
temp->prevNode->nextNode = temp->nextNode;
temp->nextNode->prevNode = temp->prevNode;
}
free(temp);
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.