实验:链表

实验:链表(4学时)
[问题描述]
创建一个长度为10的单链表,该单链表的表目为随机产生的整型数,试编写算法实现由键盘输入整数值,由此生成长度为10的单链表并检索该链表中有相同整数值的表目个数。
[实验目的]
(1)掌握线性表的链式存储结构。
(2)掌握在链表上基本操作的实现。
(3)在掌握链表的基本操作上进行综合题的实现。
[实验内容及要求]
(1)创建单链表结构实现基本操作。
(2)要求链表中数据由随机数产生,并实现输入整数值的查找。
[实验代码、测试数据及结果]

#include <stdio.h> 
#include <time.h>
#include <stdlib.h>  

typedef struct Node_def{
    int data;
    struct Node_def * p_next;

}Node;

void printout(Node* head){
        Node *q = head->p_next;
        while (q){
            printf("%d ", q->data);
            q = q->p_next;
        }
        printf("
");
}

int main(){
    int n, i,key, count = 0;
    Node head;
    Node* p, *q;
    p = q = &head;
    srand((unsigned)time(NULL));
    printf("input the length:");
    scanf("%d", &n);


    for (i=0; i<n; i++){
        p = (Node*)malloc(sizeof(Node));
        p->data = rand()%100;
        p->p_next = NULL;
        q->p_next = p;
        q = p;
    }

    printout(&head);

    puts("enter a key:");
    scanf("%d", &key);
    q = head.p_next;
    while(q){
        if (key == q->data) count++;
        q=q->p_next;
    }

    printf("The data value %d occure %d times.
", key, count);
    return 0;
}

运行图

原文地址:https://www.cnblogs.com/laohaozi/p/8266573.html