Programming C Objectives Implement a linked list from scratch, including some ex
ID: 3820927 • Letter: P
Question
Programming C
Objectives
Implement a linked list from scratch, including some extra functionality.
Assignment
Using the code from the Linked lists lecture as a starting point, we're going to create some additional functions to make linked lists even more powerful. Unless you want to, you don't actually need to include the append and delete functions from lecture.
Our linked list for this assignment will contain nodes defined by the following struct: (place it after your preprocessor directives)
Create a new node_t with its value proeprty set to the value passed in by the user. For the sake of these instructions, let new_node be this new node.
If idx is greater than 0:
Traverse the first idx-1 nodes of the list, following the linkp pointer from each node to the next. For the sake of these instructions, let current be a pointer to the node at idx-1.
Set new_node->linkp to point to current->linkp.
Set current->linkp to point to new_node (&new_node)
If idx is 0:
Set new_node->linkp to point to *list (The first node in the list)
Set *list to point to new_node (Since new_node is now the first node in the list)
Testing it out
Use this main function to test out your implementations:
Explanation / Answer
#include<stdio.h>
typedef struct node {
int value;
struct node *linkp;
}node_t;
void print_list(node_t *list) {
while (list != NULL) { //traverse til the end
printf("%d ", list->value); //and print value in new line
list = list -> linkp;
}
}
int get_size(node_t *list) {
int count = 0;
while (list != NULL) { //traverse til the end
count ++; //and count the nodes
list = list -> linkp;
}
return count;
}
node_t *search(node_t *list, int search_value) {
while (list != NULL) { //we traverse till the end of list
if (list->value == search_value) //if value matches
return list; // return the pointer
list = list -> linkp;
}
return NULL; //NULL if not found
}
void insert(node_t **list, int index, int value) {
int count = 0;
node_t *temp = *list;
node_t *newNode = malloc(sizeof(node_t));;
newNode -> value = value;
if (index == 0){ // if new node is the head
newNode ->linkp = *list;
*list = newNode;
return;
}
while (count < index) { //if new node is placed after indexed node
temp = temp -> linkp; // we traverse till the indexed node
count ++;
}
newNode ->linkp = temp -> linkp; //insert the new node accordingly
temp->linkp = newNode;
}
void main() {
}
I hope this code helps you. I have also commented the parts of code that may look tricky to a student. Incase you need any further information please comment below.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.