Answer to Question #256113 in C for Riya

Question #256113

Write a program to search an element in linked list.


1
Expert's answer
2021-10-25T17:56:09-0400
// Write a program to search an element in linked list.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
 int v;
 struct Node * next;
} Node;

void Print(Node *head) {
 while (head) {
  printf("%d ", head->v);
  head = head->next;
 }
}

Node* Push(Node* head, int v) {
 Node *newNode = (Node*)malloc(sizeof(Node));
 newNode->v = v;
 newNode->next = head;
 return newNode;
}

Node * Find(Node* head, int v) {
 while (head) {
  if (head->v == v) return head;
  head = head->next;
 }
 return NULL;
}

int main()
{
 Node * head = NULL;
 for (int i = 0; i < 5; i++) head = Push(head, i + 1);
 printf("List: ");
 Print(head);
 printf("\n");
 for (int i = -2; i < 7; i++) {
   printf("Search for %d: ", i);
   if (Find(head, i)) {
     printf("Found\n");
   }
   else {
     printf("Not Found\n");
   }
 }
 return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS