数据结构第六次作业

9.29

#include <bits/stdc++.h>
using namespace std;
struct Node{
    int id;
    int data;
    Node* next; 
};
Node* CreatList(){
    Node *head=new Node;
    Node *tail=head;
    int num=0;
    cin>>head->data;
    head->id=num++;
    int data;
    while(cin>>data){
        if(data==-1) break;
        Node *p=new Node;
        p->data=data;
        p->id=num++;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    tail->next=head;
    return head;
}
void ShowList(Node *head){
    cout<<head->id<<' '<<head->data<<endl;
    Node *p=head->next;
    while(p!=head){
        cout<<p->id<<' '<<p->data<<endl;
        p=p->next;
    }
}
Node* Search(Node *head,Node *tail,int key){
    Node *p=head;
    while(p!=tail){
        if(p->data==key) break;
        p=p->next;
    }
    return p;
}
void Solve(Node* h){
    int key;
    Node* t=h;
    while(cin>>key){
        if(key>t->data) t=Search(t->next,h,key);
        else if(key<t->data) t=Search(h,t,key);
        cout<<t->id<<' ';
    }
}
int main(){
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    Node *h=CreatList();
    ShowList(h);
    putchar(10);
    Solve(h);
    return 0;
}

9.31 判断一棵二叉树是不是二叉排序树。

...
int pre;
bool res=1;
void isBST(Node *root){
    if(!root) return;
    isBST(root->lchild);
    if(root->key<pre) res=0;
    pre=root->key;
    isBST(root->rchild);
}
int main(){
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    Node *root=CreatTree();
    Node *p=root;
    while(p->lchild) p=p->lchild;
    pre=p->key;
    isBST(root);
    cout<<res;
    return 0;
}

9.45

#include <bits/stdc++.h>
using namespace std;
struct Node{
    int key;
    Node *next;
};
Node *Hash[100];
int m;
int H(int x){return x%m;}
void CreatHash(){
    int key;
    while(cin>>key){
        int h=H(key);
        Node *p=new Node;
        p->key=key;
        if(!Hash[h]){
            Hash[h]=new Node;
            Hash[h]->next=NULL;
        }
        p->next=Hash[h]->next;
        Hash[h]->next=p;
    }
}
void ShowHash(){
    for(int i=0;i<m;i++){
        cout<<i<<' ';
        Node *p=Hash[i]->next;
        while(p){
            cout<<p->key<<' ';
            p=p->next;
        }
        putchar(10);
    }
}
int main(){
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    cin>>m;
    CreatHash();
    ShowHash();
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1)这本书为什么值得看: Python语言描述,如果学的Python用这本书学数据结构更合适 2016年出版,内容...
    孙怀阔阅读 12,643评论 0 15
  • 对于大量的输入数据,链表的线性访问时间太慢,不宜使用。 本章讨论一种简单的数据结构,其大部分操作的运行时间平均为O...
    好好学习Sun阅读 1,147评论 0 1
  • 1. 链表 链表是最基本的数据结构,面试官也常常用链表来考察面试者的基本能力,而且链表相关的操作相对而言比较简单,...
    Mr希灵阅读 1,477评论 0 20
  • 1 事情的起因是这样的,格格有次生病了,一天拉好几次肚子,晚上也不肯睡觉,有点儿小动静就哭闹,一直哭,要奶奶抱很久...
    周末2016阅读 711评论 0 0
  • 我看着眼前诡异的场面,已经完全忘记尖叫了,腿肚子也像抽筋一样打起了哆嗦,我想赶紧逃跑,但是却怎么都使不上劲。 “公...
    鱼饮墨阅读 2,039评论 2 4