Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Node {
- int key;
- struct Node *next;
- } Node;
- Node *create_node(int key, Node *next=nullptr) {
- Node *ptr = (Node*)malloc(sizeof(Node));
- ptr->key = key;
- ptr->next = next;
- return ptr;
- }
- Node *push_front(Node *head, int key) {
- return create_node(key, head);
- }
- Node *push_back(Node *head, int key) {
- if (!head)
- return create_node(key);
- head->next = push_back(head->next, key);
- return head;
- }
- Node *insert_in_order(Node *head, int key) {
- if (!head)
- return create_node(key);
- if (head->key >= key)
- return create_node(key, head);
- head->next = insert_in_order(head->next, key);
- return head;
- }
- Node *find_key(Node *head, int key) {
- if (!head)
- return nullptr;
- if (head->key == key)
- return head;
- return find_key(head->next, key);
- }
- Node *delete_key(Node *head, int key) {
- if (!head)
- return nullptr;
- if (head->key == key) {
- Node *tmp = head->next;
- free(head);
- return tmp;
- } else {
- head->next = delete_key(head->next, key);
- return head;
- }
- }
- void print_list(Node *head) {
- if (!head)
- printf("NULL\n");
- else {
- printf("%d -> ", head->key);
- print_list(head->next);
- }
- }
- Node *free_list(Node *head) {
- if (head) {
- free_list(head->next);
- free(head);
- }
- return nullptr;
- }
- int main()
- {
- Node *p = nullptr, *head = nullptr;
- head = insert_in_order(head, 10);
- head = insert_in_order(head, 20);
- head = insert_in_order(head, 30);
- print_list(head);
- p = find_key(head, 50);
- print_list(p);
- p = find_key(head, 30);
- print_list(p);
- p = find_key(head, 20);
- print_list(p);
- head = delete_key(head,50);
- head = delete_key(head,20);
- print_list(head);
- head = free_list(head);
- print_list(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement