实验 线性表的有关操作

来源:互联网 发布:mysql sid_map 编辑:程序博客网 时间:2024/05/17 02:40

1、随机产生或键盘输入一组元素,建立一个带头结点的单向链表(无序)。

2、遍历单向链表(显示)。

3、把单向链表中元素逆置(不允许申请新的结点空间)。

4、在单向链表中删除所有的偶数元素(值为偶数)结点。

5、编写在非递减有序链表中插入一个元素使链表元素仍有序的函数,并利用该函数建立一个非递减有序单向链表。

6、利用算法5建立两个非递减有序单向链表,然后合并成一个非递增链表。

7、利用算法5建立两个非递减有序单向链表,然后合并成一个非递减链表。

8、编写一个主函数,调试上述算法。

代码:

#include <bits/stdc++.h>using namespace std;typedef struct Node{    int val;    Node *next;    Node(int _v=0,Node *_n=NULL){        val=_v;next=_n;    }}Node;typedef struct ilist{    Node *head;    ilist(){        head=(Node*)malloc(sizeof(Node));    }public:    Node* newnode(){//......................生成新节点        Node* p=(Node*)malloc(sizeof(Node));        p->val=rand();        p->next=NULL;        return p;    }    void randini(int num,int order){//......随机生成数字        Node *now=head;        while(num--){            now->next=newnode();            now=now->next;        }        if(order) sort();        if(order==2) reverse();    }    void traval(){//........................遍历链表        Node *now=head->next;        while(now!=NULL){            printf("%d\n",now->val);            now=now->next;        }        puts("");    }    void reverse(){//.......................翻转链表        Node *now=head->next;        Node *next=NULL,*last=NULL;        while(now!=NULL){            next=now->next;            now->next=last;            last=now;            now=next;        }        head->next=last;    }    void delete_even(){//...................删除偶数        Node *now=head->next;        Node *last=head;        while(now!=NULL){            if(now->val%2==0) last->next=now->next;            else last=last->next;            now=now->next;        }    }    void sort(){//..........................链表排序        for(Node *i=head->next;i!=NULL;i=i->next){            for(Node *j=head->next;j!=NULL;j=j->next){                if(i->val<j->val) swap(i->val,j->val);            }        }    }    void insert(int val){//.................非递减插入        Node *now=head->next,*last=head,*p=newnode();        p->val=val;        while(1){            if(now==NULL||now->val>=val){                last->next=p;                p->next=now;                return ;            }            now=now->next;            last=last->next;        }    }    void UDunion(ilist a){//................非递减合并        for(Node *i=a.head->next;i!=NULL;i=i->next){            insert(i->val);        }    }    void UIunion(ilist a){//................非递增合并        for(Node *i=a.head->next;i!=NULL;i=i->next){            insert(i->val);        }        reverse();    }}ilist;int main(){    srand((unsigned)time(0));    ilist a,b;    a.randini(10,0);    b.randini(5,0);a.traval();    a.reverse();a.traval();    a.sort();a.traval();    a.delete_even();a.traval();    a.insert(4523);a.traval();    a.UIunion(b);a.traval();}


原创粉丝点击