9106:查找单链表中的值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/83350308

 Problem Description

从非空单链表中查找其值在[s,t]之间(含s和t)的所有元素,要求输出值在[s,t]之间的元素个数。

 Input

输入的第一行为一个数字n,表示下面有n组数据,每组数据包括3行:第1行包含两个数字s和t,第2行为单链表的表长len(0<len<=20),第3行为单链表的数据元素。

 Output

每组输出为一行,对于每组输入数据,输出值在[s,t]之间的元素个数。

 Sample Input

1
8 18
7
11 3 15 10 17 9 25

 Sample Output

5
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

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

class List {
public:
    node* head;
    List() {
        head=new node;
        head->next=NULL;
    }
    void creat(int n) {
        node* r=head;
        int num;
        for(int i=0; i<n; i++) {
            cin>>num;
            node* s=new node;
            s->data=num;
            r->next=s;
            r=s;
        }
        r->next=NULL;
    }

    int Count(int left,int right) {
        int count=0;
        node* p=head->next;
        while(p) {
            if(p->data>=left&&p->data<=right) {
                count++;
            }
            p=p->next;
        }
        return count;


    }
    ~List() {
        //     if(head==NULL||head->next==NULL)return;
        node* p=head->next;
        while(p) {
            node* temp=p;
            p=p->next;
            delete temp;
        }
    }

    void print() {

        if(head->next==NULL||head==NULL) {
            return;
        }
        node* p=head->next;
        while(p->next) {

            cout<<p->data<<" ";
            p=p->next;

        }
        cout<<p->data<<endl;
    }


};


int main() {
       int T;
    while(cin>>T) {
        while(T--) {
                int left,right;
        cin>>left>>right;
            int n;
            cin>>n;
            List* list=new List;
            list->creat(n);
            int ret=list->Count(left,right);
            cout<<ret<<endl;
            delete list;
        }

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39993896/article/details/83350308