I have taken a data structures class which focused primarily on implementing in java but I am trying to apply my knowledge by implementing a few structures in a different language.
currently I am trying to implement a linked list. I have managed to get it working fine so far, but am having trouble with the insert function. I can only insert at the top of the list, after the header. To insert after any given node I must set my current node to current->next after the insertion is completed. How can I accomplish this within the function itself? Thanks for your help. I've posted my code below.
Code:#include <stdio.h> #include <stdlib.h> void printList(struct node* list); int isEmpty(struct node* list); void makeEmpty(struct node* list); struct node* find(struct node* list, int item); void insert(struct node* p, int item); void removeNode(struct node *list, int item); struct node { int data; struct node* next; }; int main() { struct node *root; struct node *current; struct node **ptr_to_head = &root; int k; root = (struct node*)malloc(sizeof(struct node)); root->next = NULL; root->data = NULL; current = root; for(k = 1; k < 10; k++) { insert(current, k * 5); current = current->next; } printList(root); return 0; } int isEmpty(struct node* list) { if(list->next == NULL) return 1; return 0; } void makeEmpty(struct node* list) { list->next = NULL; } void printList(struct node *list) { struct node* current; if(isEmpty(list)) printf("List is empty.\n"); else { current = list->next; while(current->next != NULL) { printf("%d\n", current->data); current = current->next; } printf("%d\n", current->data); } } /*returns a node containing the item in the list. If item is *not found then a null value is returned */ struct node* find(struct node *list, int item) { struct node *p = list->next; if(p != NULL) { while(p->next != NULL) { if(p->data == item) return p; p = p->next; } } return NULL; } //inserts item at the front of the list void insert(struct node *list, int item) { if(list != NULL) { struct node* p = (struct node*)malloc(sizeof(struct node)); p->data = item; p->next = list->next; list->next = p; } } void removeNode(struct node *list, int item) { struct node *current = list->next; struct node *previous = list; if(isEmpty(list)) printf("List is empty."); else { while(current->next != NULL && current->data != item) { previous = current; current = current->next; } if(current->data == item) { previous->next = current->next; free(current); } else printf("Value not in list.\n"); } }



2Likes
LinkBack URL
About LinkBacks



ata_structures