Skip to content

Instantly share code, notes, and snippets.

@sprintr
Last active December 31, 2015 00:39
Show Gist options
  • Select an option

  • Save sprintr/7908568 to your computer and use it in GitHub Desktop.

Select an option

Save sprintr/7908568 to your computer and use it in GitHub Desktop.
Searching in unsorted linked list!
#include <iostream>
using namespace std;
class LinkedList
{
public:
LinkedList()
{
start = NULL;
}
void add(int d)
{
Node* n = new Node;
if(start == NULL)
{
start = n;
n->next = NULL;
n->data = d;
}
else
{
n->next = start;
n->data = d;
start = n;
}
}
void display()
{
Node* ptr = start;
while(ptr != NULL)
{
cout << ptr->data << endl;
ptr = ptr->next;
}
}
void search(int q)
{
Node* loc = NULL;
Node* ptr = start;
int c = 1;
while(ptr != NULL)
{
if(q == ptr->data)
{
loc = ptr;
break;
}
else
{
ptr = ptr->next;
c++;
}
}
if(loc == NULL)
{
cout << "Item not found" << endl;
}
else
{
loc = ptr;
cout << "Item found at " << c << " and is located at " << loc << endl;
}
}
private:
struct Node
{
int data;
Node* next;
};
Node* start;
};
int main(int argc, char **argv)
{
LinkedList a;
a.add(20);
a.add(22);
a.add(24);
a.add(26);
a.add(28);
a.add(30);
a.add(32);
a.add(34);
a.add(35);
a.search(26);
a.display();
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment