//链表: #include <iostream> using namespace std; //定义结点: struct NODE { int data;//数据域 NODE *next;//指针域 }; //链表类: class LIST { NODE *head; public: //构造函数 LIST() { head = new NODE;//申请结点空间 head->next = NULL;//指针域设为空 } void readInit(int n); int getByNum(int n); int getByData(int data); }; //创建链表 void LIST::readInit(int n) { cout << "请输入"<< n << "个结点值" << endl; int data; for(int i = 0; i < n; i++) { cin >> data; NODE *newNode = new NODE;//为每一个结点申请空间 newNode->data = data; newNode->next = NULL;//指针域设置为空 NODE *cur = head;//又定义一个数组指针指向表头 while(cur->next) { cur = cur->next; } cur->next = newNode; } } //通过序号查找数值: int LIST::getByNum( int n ) { int i = 0; NODE* cur = head; while(cur->next && i < n) { cur = cur->next; //不断地把后面的指针域赋值给前面的;直到i=n也就是当找到需要的元素时 i++; } return cur->data;//输出要查找的元素 } //通过数值查找序号: int LIST::getByData( int data ) { int i = 0; NODE *cur = head;//为什么都要把head放到*cur里面? while(cur->next) { cur = cur->next; i++;//用来记录序号数,然后如果找到就把这个序号输出 if(cur->data == data) { return i; } } return -1; } int main() { int n, i, data; LIST list; cout << "请输入要建立的链表长度" << endl; cin >> n; list.readInit(n); cout << "请输入要查询的链表序号" << endl; cin >> i; cout << "第" << i << "个结点值为" << list.getByNum(i) << endl; cout << "请输入要查询的结点值" << endl; cin >> data; i = list.getByData(data); if(i == -1) { cout << "找不到该结点" << endl; } else { cout << "该结点值位于第" << i << "位" << endl; } system("pause"); return 0; }
时间: 2024-10-01 03:36:52