单链表2--查找单链表结点个数、判断一个数据是否在链表中和查询任意节点的数据

接上一篇,我们继续聊聊单链表!
这一篇总共介绍三个事情:

  1. 查找单链表结点个数到底有几个?//心中有数
  2. 判断一个数据是否在链表中?//看看是否有自己想要的
  3. 查询任意节点的数据是多少?//随便看任意结点的数据

  • 查找『单链表中结点数量』–find

    #include<iostream>
    using namespace std;
    struct Node
    {
          
          
        int data;
        Node *next;
    };
    Node *head, *p, *r;//Node类型的三个指针:头指针、中间指针和尾指针
    int x,y;
    int find(Node *head){
          
          
        int n = 0;
        p = head;
        while (p != NULL)
        {
          
          
            n += 1;
            p = p->next;
        }
        return n;
    }
    int main(){
          
          
        cin >> x;
        head = new Node;//
        r = head;//
        while (x != -1)
        {
          
          
            p = new Node;//
            cin >> y;
            p ->data = y;//
            p ->next = NULL;//
            r ->next = p;//
            r = p;//
            cin >> x;
        }
        cout <<"这个单链表的结点数量为"<<find(head)<<endl;
        return 0;
    }
    

    上面的find函数拿到的节点数不含尾结点!
    总节点总数量+1即可

  • 查找『数据域的值满足一定条件的结点』–select
    告诉你第几个结点,请你告诉我那个结点的数值是多少!

    #include<iostream>
            using namespace std;
            struct Node
            {
          
          
                /* 定义数值域和指针域 */
                int data;
                Node *next;
            };
            Node *head, *p, *r;//Node类型的三个指针:头指针、中间指针和尾指针 默认值为NULL
            int x,y;
            int main(){
          
          
                cin >> x;
                head = new Node;//动态申请头结点地址
                r = head;//指针赋值,头尾为同一地址
                while (x != -1)
                {
          
          
                    /* p结点的定义 */
                    p = new Node;//动态申请新新结点p
                    cin >> y;
                    p ->data = y;//给p结点的数值域赋值
                    p ->next = NULL;//给p结点的指针域赋空值
                    /* 与其他结点进行关联 */
                    r ->next = p;//p结点的地址赋值给r结点的next,尾结点的next指向p结点--链接在一起
                    r = p;//p结点的地址与尾结点的地址一致,地址替换了!!
                    cin >> x;
                }
                p = head->next;//头结点的地址赋值给p--与头结链接在一起
                int z;
                cout << "输入你要查找的数据"<<endl;
                cin >> z;
                while ((p->data != z) && (p->next != NULL))
                    p = p->next;
                if(p->data == z)
                    cout << "找到了";
                else
                    cout << "没找到";   
                
                return 0;
            }
    	```
        
    

大家思考一下如何把查找部分的代码封装成一个函数,实参是z

void select(int w){
    
    
            while ((p->data != w) && (p->next != NULL))
            p = p->next;
            if(p->data == w)
                cout << "找到了";
            else
                cout << "没找到";   
    }

猜你喜欢

转载自blog.csdn.net/qingdao_program/article/details/113172145
今日推荐