Search the data in the linked list

How can I search the data? I want to get the output like this. Anyone can explain to me? Thanks in advance.
==============================
Enter a data to search: 44
DATA FOUND!
==============================
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  #include <iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};

int main ()
{
    node *head, *temp, *prev;
    int i,x, target;
    //Creating the first node
    head = new node;

    for (int a=0; a<1; a++)
    {
        cout<<"Enter data " << a + 1 << ": ";
        cin>>x;
    }


    head->data = x;
    head->next = NULL;
    temp = head;

    for(i=0; i<4; i++)
    {
        temp -> next =new node;
        temp = temp -> next;
        cout<<"Enter data " << i +2 << ": ";
        cin>>x;
        temp->data = x;
        temp->next = NULL;
    }

    //Printing out the linked list
    temp = head;

    cout << "The Current List:" <<endl;

    while (temp !=NULL)
    {
        cout<<temp->data << "\t";
        temp = temp->next;
    }


    cout << endl;
    cout << endl;
    cout << "Deleting the first node" << endl;
    cout << "The list after deletion:" << endl;

    //Deleting a node
    temp = head;
    head = head->next;
    delete temp;

    //Printing out the linked list

    temp = head;

    while (temp != NULL)
    {
        cout<<temp->data<< "\t";
        temp = temp->next;
    };

    cout << endl;
    cout << endl;
    cout << "Enter a data to search: ";
    cin >> target;

    int found = 0;

    for(int i=0; i<4; i++)
    {
        if(array[i] == target)
        found = 1;
    }
}
To search in a linked list, you'll start at the first node and traverse the list, checking to see if the value you're looking for is in the data member of current node or if you've reached the end of the list without finding the value.
Do you have example for me to learn it? I didn't understand this coding.

cin>>target;
found = 0;
for(i=0; i<n; i++)
{
if(array[i] == target)
found = 1;
}
Last edited on
That code is searching all the elements of an array (assuming that the n in the for loop is the size of the array) for a value equal to what the user entered for target. If there is a match, an int variable found gets set to 1.

You already have code that traverses the linked list when you print all the values in the list. Instead of printing the values, now you want to check if the data in the node is equal to the value input. temp->data == target. A bool variable can be set to true if the value is found.

I don't know if the assignment requires this all be in the main function, but I'd usually break a program like this into separate functions.
Topic archived. No new replies allowed.