#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#define MX 655 //maximum size array
using namespace std;
//Implement struct List
struct MyList
{
int date;
MyList* pNext;
};
//
void InitList(MyList** hd)
{
//
*hd = NULL;//to 0
}
//Implement function push List
void push(MyList** hd, int dt)
{
if (*hd == NULL)
{
//Если первый элемент
(*hd) = new MyList;
(*hd)->date = dt;
(*hd)->pNext = NULL;
}
else
{
MyList* p = *hd;
while (p->pNext)
p = p->pNext;
MyList* nw = new MyList;
nw->date = dt;
nw->pNext = NULL;
p->pNext = nw;
}
}
//Function Delete Node
bool Delete_Node(MyList** hd, MyList* el)
{
if (el == (*hd))
{
MyList* tm = el->pNext;
delete el;
(*hd) = tm;
return true;
}
else
{
MyList* p = (*hd);
MyList* prNode = (*hd);
while ((p) && (p != el))
{
prNode = p;
p = p->pNext;
}
if (p)
{
prNode->pNext = p->pNext;
delete p;
return true;
}
else
return false;
}
}
//Pop element
int pop(MyList** hd)
{
MyList* d = (*hd);
while (d->pNext)
d = d->pNext;
int ans = d->date;
Delete_Node(&(*hd), d);
return ans;
}
//clear
void clear(MyList** hd)
{
MyList* p = *hd;
MyList* tmp;
while (p)
{
tmp = p;
p = p->pNext;
Delete_Node(&(*hd), tmp);
}
(*hd) = NULL;
}
void Print(MyList* hd)
{
MyList* p = hd;
while (p)
{
cout << p->date << " ";
p = p->pNext;
}
}
//Implement Linear Search in Linked List
bool findList(MyList* hd, const int key)
{
MyList* p = hd;//Pointer head Linked List
while (p)
{
if (p->date == key)
return true;
p = p->pNext;
}
return false;
}
//Find key in array
bool findArray(int *ar,const int sizeA,const int key)
{
for (int i = 0; i < sizeA; i++)
{
if (ar[i] == key)
return true;
}
return false;
}
int main()
{
//Example test
int sz;
cout << "How many numbers do you want to enter: ";
cin >> sz;
cout << "Please enter numbers:\n";
int ms[MX];
int* arr = new int[sz];//Array
MyList* lk;//Linked List
InitList(&lk);//Init
for (int i = 0; i < sz; i++)
{
cin >> ms[i];
}
int key;
cout << "enter key: ";
cin >> key;
for (int i = 0; i < sz; i++)
{
arr[i] = ms[i];
push(&lk, ms[i]);
}
cout << "===============Find key in unsorted===========================\n";
(findArray(arr, sz, key)) ? cout << "True in Array\n" : cout << "False in Array\n";
(findList(lk,key))? cout << "True in List\n" : cout << "False in List\n";
clear(&lk);
delete[]arr;
return 0;
}
Comments
Leave a comment