c code for mth linked list.

  • clinked-list
  • write a c code to print mth linked list.

    Write a program to print the mth node from the last of a linked list of n nodes.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; int count = 0; void display(struct node *r) { printf("elements of list are : "); while (r) { printf("%d ---> ", r->data); r = r->next; count++; } printf("NULL\n"); } void from_last(struct node *r, int m) { if (m > count) { printf("INVALID POS"); } else { struct node *t = r; int i = count - m; int j = 0; while (t) { if (j == i) { printf("%d", r->data); exit(0); } r = r->next; j++; } } } struct node *create(struct node *head) { struct node *t, *p; int n; if (head == NULL) { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node: \n"); scanf("%d", &t->data); t->next = NULL; head = t; } if (head != NULL) { do { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node: \n"); scanf("%d", &t->data); t->next = NULL; p = head; while (p->next != NULL) { p = p->next; } p->next = t; printf("do you want to add more node press 1 for yes, 0 for no. "); scanf("%d", &n); } while (n); } return head; } int main() { struct node *head = NULL, *p; int m; head = create(head); printf("enter the value of m : "); scanf("\n%d", &m); display(head); from_last(head, m); return 0; }