线性查找
C++代码
哈工大版C++实现代码
/***** 线性查找 *****/
#include<iostream>
using namespace std;
struct celltype { //单向链表
int data;
celltype* next;
};
int search(int keyword, int last, int list[]) { //顺序表的线性查找
int i = last;
list[0] = keyword; //list[0]为哨兵或伪记录
while (list[i] != keyword)
--i;
return i;
}
celltype* search(int keyword, celltype* cell) { //链表的线性查找
celltype* p = cell;
while (p != NULL) {
if (p->data == keyword)
return p;
else p = p->next;
}
}
int main() {
int list[10001]; //测试顺序表
for (int i = 1; i <= 10000; i++)
list[i] = i;
int adj = 0; //数组下标
int keyword = 9999;
cout << list[search(keyword, 10000, list)] << endl;//测试顺序表
celltype* cell=new celltype; //测试链表
celltype* pre = cell;
for (int i = 1; i <= 10000; i++) {
celltype* p = new celltype;
p->data = i;
pre->next = p;
pre = p;
pre->next = NULL;
}
cout << search(keyword, cell)->data << endl; //测试链表
return 0;
}