c code to find second smallest and second largest in linked list

  • clinked list
  • write a c code to find second smallest and second largest in linked list

    Write a program to find out the second smallest and second largest element stored in a linked list of n integers. n is the user input. The array takes input through random number generation within a given range. How many different ways you can solve this problem. Write your approaches & strategy for solving this problem.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; void display(struct node *r) { printf("elements of list are : "); while (r) { printf("%d ---> ", r->data); r = r->next; } printf("NULL\n"); } int init_count(struct node *r) { int count = 0; while (r) { r = r->next; count++; } return count; } struct node *create(struct node *head) { int n; printf("enter the number of elments in linked list\n"); scanf("%d", &n); struct node *t, *p; if (head == NULL) { t = (struct node *)malloc(sizeof(struct node)); t->data = rand(); t->next = NULL; head = t; } if (head != NULL) { do { t = (struct node *)malloc(sizeof(struct node)); t->data = rand(); t->next = NULL; p = head; if (head == NULL || head->data >= t->data) { t->next = head; head = t; } else { struct node *current = head; /* Locate the node before the point of insertion */ while (current->next != NULL && current->next->data < t->data) { current = current->next; } t->next = current->next; current->next = t; } n--; } while (n > 0); } return head; } int main() { struct node *head = NULL; struct node *p; int count = 1, sm, sl; head = create(head); display(head); p = head; while (p->next != NULL) { if (count == 2) { sm = p->data; } if ((init_count(head) - 1) == count) { sl = p->data; } count++; p = p->next; } printf("second largest and second smallest number in linked is : %d and %d", sl, sm); return 0; }