Write a program to search an element in linked list.
// 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;
}
Comments
Leave a comment