Download presentation
Presentation is loading. Please wait.
1
Linked List
2
Linked List #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *link; }; // release the nodes of a linked list void release_linked_list(struct node **head) {struct node *p; while(*head) { p = *head; *head = (*head)->link; free(p); } *head = NULL; }
3
int size(struct node *head) // return the number of nodes in a linked list { // insert your code } // insert a new node after trail // if trail == NULL, the newnode is the new head of this linked list void linked_list_insert(struct node **head, struct node* trail, int data) { struct node* p = (struct node *) malloc(sizeof(struct node)); p->data = data; if (*head) { if (trail==NULL) { p->link = *head; *head = p; } else { p->link = trail->link; trail->link = p;} else { p->link = NULL; (*head) = p; } return;
4
// delete all nodes with data=k void linked_list_delete_data(struct node **head, int k) { // insert your code } void linked_list_reverse_data(struct node **head) // return a node with data == k struct node* linked_list_find(struct node *p, int k) { while(p && p->data != k) p = p->link; return p; } void output_linked_list(struct node* head) { while(head) { printf("%d\n",head->data); head = head->link;} return;}
5
int main() // Do not modify the main program { int op,data; struct node *head = NULL; scanf("%d%d", &op,&data); while(op != 0) { switch(op) { case 1: linked_list_insert(&head,NULL,data); // insert break; case 2: linked_list_delete_data(&head, data); // delete case 3: printf("%d %s\n", data, linked_list_find(head,data) ? "found" : "not found"); // search case 4: printf("%d elements in linked list\n",size(head)); // size case 5: linked_list_reverse_data(head); // reverse all nodes case 6: output_linked_list(head); // list all nodes } release_linked_list(&head); return 0;
6
Write a function size which returns the number of nodes in a linked list.
Sample Input & Output (The black characters are input, the red characters are the output, and the blue characters are comments.) 1 1 1 2 1 3 1 4 1 5 4 0 5 elements in linked list 0 0
7
Write a function linked_list_delete_data which deletes all nodes with data == k.
Sample Input & Output (The black characters are input, the red characters are the output, and the blue characters are comments.) 1 1 1 2 1 3 1 4 1 5 4 0 6 elements in linked list 2 1 5 0 6 0 2 3 4 5 0 0
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.