数据结构代码汇总

1.C++编程能力评估(指针):链表中删除数据元素

实现链表的输入(已实现)、输出和删除成员函数。

输入时,根据endtag确定是否结束输入;
删除时,根据下标(从0开始)。

注意,输入的顺序跟存放的顺序以及输出的顺序是相反的。

#include "stdlib.h"
#include "iostream"
using namespace std ;

class List; //前视定义,否则友元无法定义
class LinkNode
{
 friend  List; //链表结点类的定义
 private:
   LinkNode *link;
   int data;
 public:
   LinkNode(const int & item, LinkNode *ptr = NULL){  data=item;link=ptr;}
   LinkNode (LinkNode *ptr = NULL)    {link=ptr;}
   ~LinkNode(){};

};

class List
{//单链表类的定义
private:
    LinkNode *first; //指向首结点的指针
public:
    List () { first = new LinkNode ();}   // 带头结点
    ~List (){MakeEmpty();}         //析构函数
    void MakeEmpty ( );      //链表置空
    int Remove ( int i );
    void input(int  endTag);
    void output();
};
void List:: MakeEmpty ( )
 {
    LinkNode *q;
    while (  first->link != NULL )
	{q = first->link;
     first->link = q->link;
     delete q;
    }
};

void List :: input (int endTag){
	LinkNode  *newnode; int val;
	cin>>val;
	while(val!=endTag)
	{
		newnode=new LinkNode (val);
  	        newnode->link=first->link;
		first->link=newnode;
		cin>>val;
	}
}
int List :: Remove ( int i )
{
    if(i!=0)
    {
        LinkNode *p=first->link,*pr ;
        for(;i>0;i--)
        {
            pr=p;
            p=p->link;
        }
        pr->link=p->link;
    }
    else
        first=first->link;
    return 0;
}
void List :: output()
{
    LinkNode *p=first->link;
    while(p)
    {
        if(p->link!=NULL)
        {
            cout<<p->data<<" ";
        }
        else
             cout<<p->data;
             p=p->link;
    }
    cout<<endl;
}

2.C++编程能力评估(数组):数组中插入数据元素

向类SeqList中插入数据,请根据main函数中的调用,完成Insert和output函数。

#include<iostream>
#include<stdlib.h>
using namespace std;
class SeqList
{
private:
   int * data;  
   int last; // index of the last element
public:
   SeqList ( int sz );
   ~SeqList ( ) { delete [ ] data; }
   void input ();
   void output() ;
   void Insert   ( const int &x, int i);
}  ;
SeqList::SeqList ( int sz )
{
   if ( sz > 0 )
   { data = new int[sz];
     last = -1;
   }
}
void SeqList:: input()
{
  cin >>last;
  for (int i=0;i<last;i++)
    cin>>data [i];
  last--;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class SeqList
{
private:
   int * data;  
   int last; // index of the last element
public:
   SeqList ( int sz );
   ~SeqList ( ) { delete [ ] data; }
   void input ();
   void output() ;
   void Insert   ( const int &x, int i);
}  ;
SeqList::SeqList ( int sz )
{
   if ( sz > 0 )
   { data = new int[sz];
     last = -1;
   }
}
void SeqList:: input()
{
  cin >>last;
  for (int i=0;i<last;i++)
    cin>>data [i];
  last--;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class SeqList
{
private:
   int * data;  
   int last; // index of the last element
public:
   SeqList ( int sz );
   ~SeqList ( ) { delete [ ] data; }
   void input ();
   void output() ;
   void Insert   ( const int &x, int i);
}  ;
SeqList::SeqList ( int sz )
{
   if ( sz > 0 )
   { data = new int[sz];
     last = -1;
   }
}
void SeqList:: input()
{
  cin >>last;
  for (int i=0;i<last;i++)
    cin>>data [i];
  last--;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class SeqList
{
private:
   int * data;  
   int last; // index of the last element
public:
   SeqList ( int sz );
   ~SeqList ( ) { delete [ ] data; }
   void input ();
   void output() ;
   void Insert   ( const int &x, int i);
}  ;
SeqList::SeqList ( int sz )
{
   if ( sz > 0 )
   { data = new int[sz];
     last = -1;
   }
}
void SeqList:: input()
{
  cin >>last;
  for (int i=0;i<last;i++)
    cin>>data [i];
  last--;
}
void SeqList::Insert(const int &x, int i)
{
    int number=i;
    //int data_cpy[100];
    int *data_cpy;
    data_cpy=new int[100];
    for(int j=0;j<number;j++)
    {
        data_cpy[j]=data[j];
    }
    data_cpy[number]=x;
    for(int j=number;j<=last;j++)
    {
        data_cpy[j+1]=data[j];
    }
    /*for(int iii=0;iii<=last;iii++)
    {
        cout<<data_cpy[iii]<<" ";
        if(iii==last)
            cout<<endl;
    }*/
    data=data_cpy;//疑似错误点
}
void SeqList::output()
{
    last=last+1;
    cout<<*(data+0);
    for(int ii=1;ii<last;ii++){
        cout<<" "<<*(data+ii);
    }
    cout<<endl;

}
 int main()
 {
  SeqList myList(50);
  myList.input();
  myList.output();
  int where,value;
  cin >>where;
  cin >>value;
  myList.Insert(value,where);
  myList.output ();
  return 1;
 }

3.实现多项式的基本运算

实现多项式的输入、输出、加法、求导、求值。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct PolyNode *Polynomial;
struct PolyNode
{
    int coef;
    int expon;
    Polynomial link;
};
void attach(int c,int e,Polynomial *prear)
{
    Polynomial p;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    p->coef=c;
    p->expon=e;
    p->link=NULL;
    (*prear)->link=p;
    *prear=p;
}
Polynomial readpoly()
{
    Polynomial p,t,rear;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    p->link=NULL;
    rear=p;
    int c,e,N;
    scanf("%d",&N);
    while(N--)
    {
        scanf("%d %d",&c,&e);
        attach(c,e,&rear);
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
Polynomial add(Polynomial p1,Polynomial p2)
{
    Polynomial p,t,rear;
    int sum;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(p1&&p2)
    {
        if(p1->expon<p2->expon)
        {
            attach(p1->coef,p1->expon,&rear);
            p1=p1->link;

        }
        else if(p1->expon>p2->expon)
        {
            attach(p2->coef,p2->expon,&rear);
            p2=p2->link;
        }
        else
        {
            sum=p1->coef+p2->coef;
            if(sum)
                attach(sum,p1->expon,&rear);
            p1=p1->link;
            p2=p2->link;
        }
    }
    while(p1)
    {
        attach(p1->coef,p1->expon,&rear);
        p1=p1->link;
    }
    while(p2)
    {
        attach(p2->coef,p2->expon,&rear);
        p2=p2->link;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
Polynomial qiudao(Polynomial p1)
{
    Polynomial p,t,rear;
    int c,e;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(p1)
    {
        c=p1->coef*p1->expon;
        e=--p1->expon;
        ++p1->expon;
        if(c)
            attach(c,e,&rear);
        p1=p1->link;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
void printpoly(Polynomial p)
{
    int flag=1;
    for(; p; p = p->link)
    {
        if(p->coef < 0)
            printf("-");
        else if(!flag)
            printf("+");
        flag=0;
        if(!(abs(p->coef) == 1 && p->expon> 0))
            printf("%d", abs(p->coef));
        if(p->expon> 0)
        {
            printf("x");
            if(p->expon > 1)
                printf("^%d", p->expon);
        }
    }
    printf("\n");
}
int qiuzhi(Polynomial p1,int x)
{
    int p=0;
    while(p1)
    {
        p+=(p1->coef*pow(x,p1->expon));
        p1=p1->link;

    }
    return p;
}
int main()
{
    Polynomial p1,p2,pa,pq;
    int x;
    p1=readpoly();
    p2=readpoly();
    scanf("%d",&x);
    pa=add(p1,p2);
    pq=qiudao(p1);
    printf("A(x)+B(x)=");
    printpoly(pa);
    printf("A'(x)=");
    printpoly(pq);
    printf("A(%d)=%d\n",x,qiuzhi(p1,x));

}

4.线性表ADT实现之一:线性表ADT基于顺序存储的实现

实习目的:帮助学生熟练掌握顺序表的建立及基本操作
问题描述:设计一个顺序表并实现对其进行基本操作。
基本要求:建立一个顺序表:
(1)输入数据;
(2)实现数据的插入、删除、搜索、输出等基本操作;
(3)实现集合的并、交和两个有序顺序表的合并。
测试数据:
5  //线性表A的长度
1 3 5 7 9  //线性表A的数据
2 10 //表示在第2个位置插入10
10 //表示删除值=10的数据元素
9 //查找元素9
11/ 查找元素22
6 //线性表B的长度

1 2 3 4 5 6

#include <stdio.h>
#include <malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10

typedef struct
{
    int *elem,*m;
    int length;
    int listsize;
} SqList;

int InitList_Sq(SqList &L)
{
    L.elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int));
    if(!L.elem)
        return(-1);
    L.length=0;
    L.listsize=LIST_INIT_SIZE;
    return 1;
}

int Insert_SqList(SqList &L,int i,int x)
{
    int *p,*q;
    if(i<1||i>L.length+1)
        return(-1);
    if(L.length+1>L.listsize)
    {
        L.m=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
        if(!L.m)
            return(-1);
        L.elem=L.m;
        L.listsize +=LISTINCREMENT;
    }
    q=&(L.elem[i-1]);
    for(p=&(L.elem[L.length-1]); p>=q; --p)
        *(p+1)=*p;
    *q=x;
    ++L.length;
    return 1;
}


//Delete_SqList
int Delete_SqList(SqList &L,int x) 
{
    int index=-1;
    for(int i=0; i<L.length; i++)
    {
        if(L.elem[i]==x)
        {
            index=i;
            break;
        }
    }
    if(index<0)
        return 0;
    for(; index<L.length-1; index++)
    {
        L.elem[index]=L.elem[index+1];
    }
    L.length--;
    return 1;
}



int main()
{
    int i,x,temp;
    int delete_m;
    int search_m,flag_search=0;
    SqList L;

    SqList Sum;//※
    InitList_Sq(Sum);//※


    InitList_Sq(L);

    scanf("%d",&x);

    for(i=0; i<x; i++)
    {

        scanf("%d",&temp);
        Insert_SqList(L,i+1,temp);
        Insert_SqList(Sum,i+1,temp);

    }

    for(i=0; i<L.length; i++)  
    {
        if(i==0)
        {
            printf("A is created as:");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }



    scanf("%d",&i);

    scanf("%d",&x);

    Insert_SqList(L,i,x);

    for(i=0; i<L.length; i++)  
    {
        if(i==0)
        {
            printf("After inserted A is");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }

    
    scanf("%d",&delete_m);
    Delete_SqList(L,delete_m);
    for(i=0; i<L.length; i++)
    {
        if(i==0)
        {
            printf("After deleted A is");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }

    
    scanf("%d",&search_m);
    //情况1:找到了 9 is located at index of 5
    //情况2:没找到 22 is not found
    for(int i=0; i<L.length; i++)
    {
        if(search_m==L.elem[i])
        {
            printf("%d is located at index of %d\n",search_m,i+1);
            flag_search=1;
        }
        if((i==L.length-1)&&(flag_search==0))
        {
            printf("%d is not found\n",search_m);
        }
    }

    scanf("%d",&search_m);
    flag_search=0;
    for(int i=0; i<L.length; i++)
    {
        if(search_m==L.elem[i])
        {
            printf("%d is located at index of %d\n",search_m,i+1);
            flag_search=1;
        }
        if((i==L.length-1)&&(flag_search==0))
        {
            printf("%d is not found\n",search_m);
        }
    }

   
    SqList B;
    InitList_Sq(B);
    scanf("%d",&x);
    int sum_flag=0;//*
    for(i=0; i<x; i++)
    {
        //printf("Please input nums(%d):\n",i+1);
        scanf("%d",&temp);
        Insert_SqList(B,i+1,temp);
        for(int j=0;j<L.length;j++) //*
        {
            if(temp!=Sum.elem[j])
                sum_flag++;
        }
        if(sum_flag==L.length)
            Insert_SqList(Sum,L.length+1,temp);//*
        sum_flag=0;
    }


    for(i=0; i<B.length; i++)  
    {
        if(i==0)
        {
            printf("B is created as:");
        }
        printf(" %d",B.elem[i]);
        if(i==B.length-1)
        {
            printf("\n");
        }
    }

    /*B is created as: 1 2 3 4 5 6
      A cross B is 1 3 5
      A union B is 1 3 5 7 9 2 4 6
      A union B in sequence is 1 2 3 4 5 6 7 9 */
    //A corss B:
    printf("A cross B is");
    for(int i=0; i<L.length; i++)
    {
        for(int j=0; j<B.length; j++)
        {
            if(L.elem[i]==B.elem[j])
            {
                printf(" %d",L.elem[i]);
            }
        }

    }
    printf("\n");

    //A union B:
    printf("A union B is");
    int flag=0;
    for(int i=0; i<L.length; i++)
    {
        printf(" %d",L.elem[i]);
    }
    for(int i=0; i<B.length; i++)
    {
        for(int j=0; j<L.length; j++)
        {
            if(L.elem[j]==B.elem[i])
            {
                //printf(" %d",B.elem[i]);
                break;
            }
            if(L.elem[j]!=B.elem[i])
            {
                flag++;
            }

        }
        if(flag==L.length)
            printf(" %d",B.elem[i]);
        flag=0;
    }
    printf("\n");

    //A union B in sequence:

    //A union B in sequence is 1 2 3 4 5 6 7 9 */
    temp=0;
    for(int i=0;i<Sum.length;i++)
    {
        for(int j=0;j<Sum.length-1-i;j++)
        {
            if(Sum.elem[j]>Sum.elem[j+1])
            {
                temp=Sum.elem[j+1];
                Sum.elem[j+1]=Sum.elem[j];
                Sum.elem[j]=temp;
            }
        }
    }
    printf("A union B in sequence is");
    for(int i=0;i<Sum.length;i++)
    {
        printf(" %d",Sum.elem[i]);
    }
    printf("\n");
    return 0;
}

5.线性表ADT的实现之二:线性表ADT基于链式存储的实现

实习目的:熟练掌握链表的建立和基本操作。
问题描述:设计一个链表并实现对其进行基本操作。
基本要求:建立一个链表:
(1)输入数据;
(2)实现数据的插入、删除、搜索、输出等基本操作;
(3)实现集合的并、交和两个有序链表的合并。
测试数据:
0  //线性表输入结束标志
1 3 5 7 9 0  //线性表A的数据
2 10 //表示在第2个位置插入10
10 //表示删除值=10的数据元素
9 //查找元素9
22// 查找元素22
0  //线性表输入结束标志

1 2 3 4 5 6 0 

#include <malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10


typedef struct
{
    int *elem,*m;
    int length;
    int listsize;
} SqList;


int InitList_Sq(SqList &L)
{
    L.elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int));
    if(!L.elem)
        return(-1);
    L.length=0;
    L.listsize=LIST_INIT_SIZE;
    return 1;
}


int Insert_SqList(SqList &L,int i,int x)
{
    int *p,*q;
    if(i<1||i>L.length+1)
        return(-1);
    if(L.length+1>L.listsize)
    {
        L.m=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
        if(!L.m)
            return(-1);
        L.elem=L.m;
        L.listsize +=LISTINCREMENT;
    }
    q=&(L.elem[i-1]);
    for(p=&(L.elem[L.length-1]); p>=q; --p)
        *(p+1)=*p;
    *q=x;
    ++L.length;
    return 1;
}




//Delete_SqList
int Delete_SqList(SqList &L,int x) //把x从表中删去
{
    int index=-1;
    for(int i=0; i<L.length; i++)
    {
        if(L.elem[i]==x)
        {
            index=i;
            break;
        }
    }
    if(index<0)
        return 0;
    for(; index<L.length-1; index++)
    {
        L.elem[index]=L.elem[index+1];
    }
    L.length--;
    return 1;
}






int main()
{
    int i,x,temp;
    int delete_m;
    int search_m,flag_search=0;
    SqList L;


    SqList Sum;//※
    InitList_Sq(Sum);//※




    InitList_Sq(L);


    scanf("%d",&x);
    i=0;
    while(scanf("%d",&temp)!=x)
    {
        if(temp==x)
            break;
        Insert_SqList(L,i+1,temp);
        Insert_SqList(Sum,i+1,temp);
        i++;


    }


    for(i=0; i<L.length; i++)  //创建后输出
    {
        if(i==0)
        {
            printf("A is created as:");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }


    //以下为插入操作


    scanf("%d",&i);


    scanf("%d",&x);


    Insert_SqList(L,i,x);


    for(i=0; i<L.length; i++)  //插入后输出
    {
        if(i==0)
        {
            printf("After inserted A is");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }


    //以下为删除操作
    scanf("%d",&delete_m);
    Delete_SqList(L,delete_m);
    for(i=0; i<L.length; i++)
    {
        if(i==0)
        {
            printf("After deleted A is");
        }
        printf(" %d",L.elem[i]);
        if(i==L.length-1)
        {
            printf("\n");
        }
    }


    //以下为查找操作
    scanf("%d",&search_m);
    //情况1:找到了 9 is located at index of 5
    //情况2:没找到 22 is not found
    for(int i=0; i<L.length; i++)
    {
        if(search_m==L.elem[i])
        {
            printf("%d is located at index of %d\n",search_m,i+1);
            flag_search=1;
        }
        if((i==L.length-1)&&(flag_search==0))
        {
            printf("%d is not found\n",search_m);
        }
    }


    scanf("%d",&search_m);
    flag_search=0;
    for(int i=0; i<L.length; i++)
    {
        if(search_m==L.elem[i])
        {
            printf("%d is located at index of %d\n",search_m,i+1);
            flag_search=1;
        }
        if((i==L.length-1)&&(flag_search==0))
        {
            printf("%d is not found\n",search_m);
        }
    }


    //以下是关于B的操作
    SqList B;
    InitList_Sq(B);
    scanf("%d",&x);
    int sum_flag=0;//*
    i=0;
    while(scanf("%d",&temp)!=x)
    {
        if(temp==x)
            break;
        Insert_SqList(B,i+1,temp);
        for(int j=0;j<L.length;j++) //*
        {
            if(temp!=Sum.elem[j])
                sum_flag++;
        }
        if(sum_flag==L.length)
            Insert_SqList(Sum,L.length+1,temp);//*
        sum_flag=0;
        i++;
    }




    for(i=0; i<B.length; i++)  //创建后输出
    {
        if(i==0)
        {
            printf("B is created as:");
        }
        printf(" %d",B.elem[i]);
        if(i==B.length-1)
        {
            printf("\n");
        }
    }


    /*B is created as: 1 2 3 4 5 6
      A cross B is 1 3 5
      A union B is 1 3 5 7 9 2 4 6
      A union B in sequence is 1 2 3 4 5 6 7 9 */
    //A corss B:
    printf("A cross B is");
    for(int i=0; i<L.length; i++)
    {
        for(int j=0; j<B.length; j++)
        {
            if(L.elem[i]==B.elem[j])
            {
                printf(" %d",L.elem[i]);
            }
        }


    }
    printf("\n");


    //A union B:
    printf("A union B is");
    int flag=0;
    for(int i=0; i<L.length; i++)
    {
        printf(" %d",L.elem[i]);
    }
    for(int i=0; i<B.length; i++)
    {
        for(int j=0; j<L.length; j++)
        {
            if(L.elem[j]==B.elem[i])
            {
                //printf(" %d",B.elem[i]);
                break;
            }
            if(L.elem[j]!=B.elem[i])
            {
                flag++;
            }


        }
        if(flag==L.length)
            printf(" %d",B.elem[i]);
        flag=0;
    }
    printf("\n");


    //A union B in sequence:


    //A union B in sequence is 1 2 3 4 5 6 7 9 */
    temp=0;
    for(int i=0;i<Sum.length;i++)
    {
        for(int j=0;j<Sum.length-1-i;j++)
        {
            if(Sum.elem[j]>Sum.elem[j+1])
            {
                temp=Sum.elem[j+1];
                Sum.elem[j+1]=Sum.elem[j];
                Sum.elem[j]=temp;
            }
        }
    }
    printf("A union B in sequence is");
    for(int i=0;i<Sum.length;i++)
    {
        printf(" %d",Sum.elem[i]);
    }
    printf("\n");


    return 0;
}

6.线性表的操作—链表倒置。

使用链表创建时,使用前插法的时候,输入顺序跟输出顺序是相反的,因此请编写类的reverse成员函数,实现链表的转置,使其顺序与输入相同。
 

#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
class List; //前视定义,否则友元无法定义
class LinkNode
{        
 friend  class List; //链表结点类的定义
 private: 
   LinkNode *link; 
   int data;  
 public: 
   LinkNode (LinkNode *ptr = NULL)    {link=ptr;}
   LinkNode(const int & item, LinkNode *ptr = NULL){  data=item;link=ptr;} 
   ~LinkNode(){}; 
}; 

class List   
{//单链表类的定义
private:    
    LinkNode *first; //指向首结点的指针          
public:
    List (int x) { first = new LinkNode (x);}   // 带头结点
    ~List (){MakeEmpty();}         //析构函数
    void MakeEmpty ( );      //链表置空    
    void input(int  endTag);
	void reverse();
    void output();                  
}; 
void List:: MakeEmpty ( )
 { 
    LinkNode *q;
    while (  first->link != NULL ) 
	{q = first->link;  
     first->link = q->link;//将表头结点后第一个结点从链中摘下
     delete q;        //释放它 
    }
    
};	
 
void List :: input (int endTag){
	LinkNode  *newnode; int val;
	cin>>val;
	while(val!=endTag) 
	{
		newnode=new LinkNode (val);
		if (newnode==NULL)
             	{cerr<<"存储分配错误"<<endl;exit(1);}
  	    newnode->link=first->link;
		first->link=newnode;   
		cin>>val;  	
	}
} 

void List ::output ( )  {//依次输出各结点的值
LinkNode  *p=first->link; 
while(p!=NULL)    {
      cout<<p->data<<' ';
      p=p->link;
      }

cout<<endl;
}
     
     
int  main()
{
   List l(0);
    l.input(0);
    l.reverse ();
    cout<<"the result is:"<<endl;
    l.output ();
     return 1;
}
void List::reverse()
{
    LinkNode *temp,*temp0;
    if(first==NULL||first->link==NULL)
    {

    }
    else
    {
        temp=first->link;
        while(temp->link!=NULL)
        {
            temp0=temp->link;
            temp->link=temp0->link;
            temp0->link=first->link;
            first->link=temp0;
        }
        /*temp=first->link;
        first->link=NULL;
        while(temp!=NULL)
        {
            temp0=first;
            first=temp;
            temp=temp->link;
            first->link=temp0;
        }*/
    }

}

7. 栈ADT应用之一:-判断括号匹配

用栈实现:输入一行符号,以#结束,判断其中的括号是否匹配。括号包括:

{}  []  ()  <>

8. 栈ADT应用之二:回文字符串判定问题

回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的.
利用栈实现回文的判断,是则返回1,否则返回0.

实现函数huiwen()

#include<assert.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
struct StackNode {  
public:
     char  data; 
     StackNode *link; 
     StackNode(char d = 0, StackNode *next = NULL) : data(d), link(next) { }
	 ~StackNode( ){};
};  
class LinkedStack  {  
private:
	StackNode *top; 
public:
  	LinkedStack() : top(NULL) {} 
    void Push(char &x);  
    int  Pop(char & x);
	friend ostream & operator << (ostream& os, LinkedStack& s) ;	
};
ostream& operator << (ostream& os, LinkedStack& S){
// //输出栈元素的重载操作 <<
 
	 StackNode *p=S.top;int i=0;
	while(p!=NULL)
		{os<<++i<< ":" << p->data<<endl; p=p->link;}
	return os;
};	

void LinkedStack::Push(char &x) {
//将元素值x插入到链式栈的栈顶,即链头。
     top = new StackNode( x, top );	//创建新结点
     assert (top != NULL);		//创建失败退出
};

int LinkedStack::Pop(char & x) {
//删除栈顶结点, 返回被删栈顶元素的值。
     if (top == NULL ) return 0;         //栈空返回
  	 StackNode *p = top;		            //暂存栈顶元素
	 top = top->link;			      //退栈顶指针
	 x = p->data;   
     delete p;		          //释放结点
   	 return 1;	
};

int huiwen( char  s[] );
int main()
{
char  s[100] ;
gets(s); 
cout<< huiwen(s)<<endl; 
return 1;
}
int huiwen( char  s[] )
{
    int n=strlen(s);
    bool flag=1;
    int i;
    for(i=0;i<n/2;i++)
    {
        if(s[i]!=s[n-1-i])
        {
            flag=0;
            return 0;
            break;
        }
    }
    if(flag==1)
        return 1;
}

9. 线性表ADT实现-训练之一

有以下程序段,先改错,最后再编程实现所有函数的功能。
#include<iostream.h>
#include<stdlib.h>
typedef int T 
class SeqList
{
private:
T data;
int MaxSize; //顺序表最多可以存放的元素个数。
int last; //顺序表最后一个元素的下标,初始值为-1。
void SeqList(int sz);
void Input();//首先输入元素的个数,然后顺次输入元素的值。
void Output();//输出线性表的所有元素。
void Insert(const T& x, int i );//在线性表中第i个位置插入值为x的元素。
int Remove ( T & x );//从线性表中删除第一个值等于x的元素。
}
SeqList(int sz){data = new T[sz];MaxSize = sz; SeqList.last = -1; }
int main() 
{
SeqList myList(100);
myList.Input();
myList.Output ();
int i;
for( i=0;i<5;i++)
   myList.Insert(i+10,i);
myList.Output ();
for( i=10;i<15;i++)
   myList.Remove(i);
myList.Output (); 
  return 0;
}

#include<iostream>
using namespace std;
class SeqList
{
private:
    int *data;
    int last;
public:
    SeqList(int sz);
    void Input();
    void Output();
    void Insert(const int x, int i );
    void Remove ( int x );
};
SeqList::SeqList(int sz)
{
    if(sz>0)
    {
        data=new int[sz];
        last=-1;
    }
}
void SeqList::Input()
{
    int x,n;
    cin>>n;
    last=n-1;
    for(int i=0;i<=last;i++)
    {
        cin>>x;
        data[i]=x;
    }
}
void SeqList::Insert(int x,int i)
{
    int k;
    for(k=last; k>=i; k--)
        data[k+1]=data[k];
    data[i]=x;
     last++;
}
void SeqList::Remove(int x)
{
    int j;
    for(int i=0; i<=last; i++)
    {
        if(data[i]==x)
        {
            for(j=i;j<=last;j++)
            {
              data[j-1]=data[j];
            }
        }
    }
    last--;
}
void SeqList::Output()
{
    cout<<"The elements are:"<<endl;
    for(int i=0;i<=last;i++)
    cout<<data[i]<<endl;
}
int main()   
 {
  SeqList myList(100);
  myList.Input();
  myList.Output ();
  int i;
  for( i=0;i<5;i++)
	 myList.Insert(i+10,i);
  myList.Output ();
  for( i=10;i<15;i++)
     myList.Remove(i);
  myList.Output ();
  return 0;
 }
	 myList.Insert(i+10,i);
  myList.Output ();
  for( i=10;i<15;i++)
     myList.Remove(i);
  myList.Output ();
  return 0;
 }

10. 线性表操作之顺序有序表的归并

1)实现顺序表的排序(升序)
2)实现两个有序顺序表的合并:A=A∪B,要求合并后仍然有序。


从键盘直接输入:
2 1 2
3 1 2 3 
输出结果为:
1
2
3

分别表示第一个线性表元素个数为2,元素分别为 1,2 ;第二个线性表元素个数为3,元素分别为1,2,3。

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

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node
{
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;
void attach(int x,List *prear)
{
    List p;
    p=(List)malloc(sizeof(struct Node));
    p->Data=x;
    p->Next=NULL;
    (*prear)->Next=p;
    *prear=p;
}
List Read()
{
    List p,t,rear;
    p=(List)malloc(sizeof(struct Node));
    p->Next=NULL;
    rear=p;
    int x,N;
    scanf("%d",&N);
    while(N--)
    {
        scanf("%d",&x);
        attach(x,&rear);
    }
    t=p;
    p=p->Next;
    free(t);
    return p;
}
void Print(List p)
{

    while(p)
    {
        printf("%d\n",p->Data);
        p=p->Next;
    }
}
List Merge( List L1, List L2 )
{
    List front,rear,t,p=L1,q=L2;
    rear=(List)malloc(sizeof(struct Node));
    front=rear;
    while(p&&q)
    {
        if(p->Data<q->Data)
        {
            rear->Next=p;
            p=p->Next;
        }
        else if(p->Data>q->Data)
        {
            rear->Next=q;
            q=q->Next;
        }
        else
        {
            rear->Next=p;
            p=p->Next;
            q=q->Next;
        }
        rear=rear->Next;
    }
    while(p)
    {
        rear->Next=p;
        p=p->Next;
        rear=rear->Next;
    }
    while(q)
    {
        rear->Next=q;
        q=q->Next;
        rear=rear->Next;
    }
    rear->Next=NULL;
    t=front;
    front=front->Next;
    free(t);
    return front;
}

int main()
{
    List L1, L2, L;
    L1 = Read();
    L2 = Read();
    L = Merge(L1, L2);
    Print(L);
    return 0;
}

11. 线性表ADT应用:一元多项式的基本运算

使用链式存储实现一元多项式的加法、减法、乘法和求导。即:
C(x)= A(x)+B(x);C(x)= A(x)-B(x) C(x)= A(x)*B(x) C(x)= A’(x)
菜单:
1)C :分别创建两个多项式A(x)和B(x),其中 输入时按照 指数的升序顺序输入,遇到系数为0则停止。例如:输入 :
1 2 3 4 5 6 7 8
0 2 3 4 5 6 7 0 则生成的多项式分别为:
A(x)=x^2+3x^4+5x^6+7x^8
B(x)=2x^3+4x^5+6x^7
2)P:计算C(x)= A(x)+B(x),计算完毕后输出C(x)的 结果
3)S: 计算C(x)= A(x)-B(x),计算完毕后输出C(x)的 结果
4)M: 计算C(x)= A(x)*B(x),计算完毕后输出C(x)的 结果
5)D: 计算C(x)= A’(x),计算完毕后输出C(x)的 结果
6)V: 首先输入一个 float型数据,然后计算 A(x)并输出计算的结果。
7)E: 分别清空A(x)、B(x)、C(x)三个多项式。

8)X: 退出程序。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct PolyNode *Polynomial;
struct PolyNode
{
    int coef;
    int expon;
    Polynomial link;
};
void attach(int c,int e,Polynomial *prear)
{
    Polynomial p;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    p->coef=c;
    p->expon=e;
    p->link=NULL;
    (*prear)->link=p;
    *prear=p;
}
Polynomial readpoly()
{
    Polynomial p,t,rear;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    p->link=NULL;
    rear=p;
    int c,e;
    scanf("%d",&c);
    while(1)
    {
        if(c!=0)
        {
            scanf("%d",&e);
            attach(c,e,&rear);
            scanf("%d",&c);
        }
        else
            break;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
Polynomial add(Polynomial p1,Polynomial p2)
{
    Polynomial p,t,rear;
    int sum;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(p1&&p2)
    {
        if(p1->expon<p2->expon)
        {
            attach(p1->coef,p1->expon,&rear);
            p1=p1->link;

        }
        else if(p1->expon>p2->expon)
        {
            attach(p2->coef,p2->expon,&rear);
            p2=p2->link;
        }
        else
        {
            sum=p1->coef+p2->coef;
            if(sum)
                attach(sum,p1->expon,&rear);
            p1=p1->link;
            p2=p2->link;
        }
    }
    while(p1)
    {
        attach(p1->coef,p1->expon,&rear);
        p1=p1->link;
    }
    while(p2)
    {
        attach(p2->coef,p2->expon,&rear);
        p2=p2->link;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
Polynomial sub(Polynomial p1,Polynomial p2)
{
    Polynomial p,t,rear;
    int differ;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(p1&&p2)
    {
        if(p1->expon<p2->expon)
        {
            attach(p1->coef,p1->expon,&rear);
            p1=p1->link;

        }
        else if(p1->expon>p2->expon)
        {
            attach(-(p2->coef),p2->expon,&rear);
            p2=p2->link;
        }
        else
        {
            differ=p1->coef-p2->coef;
            if(differ)
                attach(differ,p1->expon,&rear);
            p1=p1->link;
            p2=p2->link;
        }
    }
    while(p1)
    {
        attach(p1->coef,p1->expon,&rear);
        p1=p1->link;
    }
    while(p2)
    {
        attach(p2->coef,p2->expon,&rear);
        p2=p2->link;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
Polynomial mult(Polynomial p1,Polynomial p2)
{
    Polynomial p,t1,t2,rear,t;
    int c,e;
    if(!p1||!p2)
        return NULL;
    t1=p1;
    t2=p2;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(t2)
    {
        attach(t1->coef*t2->coef,t1->expon+t2->expon,&rear);
        t2=t2->link;
    }
    t1=t1->link;
    while(t1)
    {
        t2=p2;
        rear=p;
        while(t2)
        {
            c=t1->coef*t2->coef;
            e=t1->expon+t2->expon;
            while(rear->link&&rear->link->expon<e)
                rear=rear->link;
            if(rear->link&&rear->link->expon==e)
            {
                if(rear->link->coef+c)
                    rear->link->coef+=c;
                else
                {
                    t=rear->link;
                    rear->link=t->link;
                    free(t);
                }
            }
            else
            {
                t=(Polynomial)malloc(sizeof(struct PolyNode));
                t->coef=c;
                t->expon=e;
                t->link=rear->link;
                rear->link=t;
                rear=rear->link;
            }
            t2=t2->link;
        }
        t1=t1->link;
    }
    t2=p;
    p=p->link;
    free(t2);
    return p;
}
Polynomial qiudao(Polynomial p1)
{
    Polynomial p,t,rear;
    int c,e;
    p=(Polynomial)malloc(sizeof(struct PolyNode));
    rear=p;
    while(p1)
    {
        c=p1->coef*p1->expon;
        e=--p1->expon;
        ++p1->expon;
        if(c)
            attach(c,e,&rear);
        p1=p1->link;
    }
    t=p;
    p=p->link;
    free(t);
    return p;
}
void printpoly(Polynomial p)
{
    int flag=1;
    for(; p; p = p->link)
    {
        if(p->coef < 0)
            printf("-");
        else if(!flag)
            printf("+");
        flag=0;
        if(!(abs(p->coef) == 1 && p->expon> 0))
            printf("%d", abs(p->coef));
        if(p->expon> 0)
        {
            printf("x");
            if(p->expon > 1)
                printf("^%d", p->expon);
        }
    }
    printf("\n");
}
float qiuzhi(Polynomial p1,int x)
{
    int p=0;
    while(p1)
    {
        p+=(p1->coef*pow(x,p1->expon));
        p1=p1->link;

    }
    return p;
}
int main()
{
    char x;
    int n;
    Polynomial p1,p2,p3;
    while(scanf("%c",&x)!=EOF)
    {
        switch(x)
        {
        case 'C':
            p1=readpoly();
            p2=readpoly();
            break;
        case 'P':
            p3=add(p1,p2);
            printf("C(x)=");
            printpoly(p3);
            break;
        case 'S':
            p3=sub(p1,p2);
            printf("C(x)=");
            printpoly(p3);
            break;
        case 'M':
            p3=mult(p1,p2);
            printf("C(x)=");
            printpoly(p3);
            break;
        case 'D':
            p3=qiudao(p1);
            printf("C(x)=");
            printpoly(p3);
            break;
        case 'V':
            scanf("%d",&n);
            printf("%0.2f\n",qiuzhi(p1,n));
            break;
        case 'E':
            free(p1);
            free(p2);
            free(p3);
            break;
        case 'X':
            exit(0);
        }
    }
}

12. 矩阵应用 稀疏矩阵的压缩存储及运算

稀疏矩阵的压缩存储:
实现稀疏矩阵压缩存储,并实现矩阵转置和求和。
输入矩阵时,首先需要输入非零元素的个数,然后分别输入矩阵的 行号,列号和值。
输完2个矩阵后,自动进行计算第一个矩阵的转置以及两个矩阵的和。
例如:输入如下:
100 90 5 //矩阵的行数为100,列数为90,共5个非零元素。
1 10 100 //a(1,10)=100
50 60 200//a(50,60)=200
50 80 100//a(50,80)=100
60 60 200//a(60,60)=200
99 89 10//a(99,89)=10
100 90 2 //矩阵b的行数为100,列数为90,共2个非零元素。
1 1 10 //b(1,1)=10

50 60 -200//b(50,60)=-200 

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 200
typedef int ElemType;
typedef struct
{
    int row,col;
    ElemType value;
} Triple;
typedef struct
{
    Triple data[MAXSIZE+1];
    int rows,cols,values;
} Matrix ;
int Creat(Matrix *M)
{
    int i,k,m,n;
    ElemType e;

    scanf("%d %d %d",&(*M).rows,&(*M).cols,&(*M).values);
    (*M).data[0].row=0;

    for(i=1; i<=(*M).values; i++)
    {
        do
        {
            scanf("%d %d %d",&m,&n,&e);
            k=0;
            if(m<1||m>(*M).rows||n<1||n>(*M).cols)
            {
                k=1;
            }
            if(m<=(*M).data[i-1].row&&n<=(*M).data[i-1].col)
            {
                k=1;
            }
        }
        while(k);
        (*M).data[i].row=m;
        (*M).data[i].col=n;
        (*M).data[i].value=e;
    }
    return 1;
}
void Delete(Matrix *M)
{
    (*M).rows=0;
    (*M).cols=0;
    (*M).values=0;
}
void Transformed(Matrix M,Matrix *T)
{
    int p,q,l;
    (*T).rows=M.cols;
    (*T).cols=M.rows;
    (*T).values=M.values;
    if((*T).values)
    {
        q=1;
        for(l=1; l<=M.cols; l++)
        {
            for(p=1; p<=M.values; p++)
            {
                if(M.data[p].col==l)
                {
                    (*T).data[q].row=M.data[p].col;
                    (*T).data[q].col=M.data[p].row;
                    (*T).data[q].value=M.data[p].value;
                    q++;
                }
            }
        }
    }
}
int Copy(Matrix M,Matrix *T)
{
    (*T)=M;
    return 1;
}
int comp(int c1,int c2)
{
    int i;
    if(c1<c2)
    {
        i=1;
    }
    else if(c1==c2)
        i=0;
    else
        i=-1;
    return i;
}
int Add(Matrix M,Matrix N,Matrix *Q)
{
    Triple *a,*b,*c,*d,*e,*f;
    if(M.rows!=N.rows||M.cols!=N.cols)
    return 0;
    (*Q).rows=M.rows;
    (*Q).cols=M.cols;
    a=&M.data[1];
    b=&N.data[1];
    c=&M.data[M.values];
    d=&N.data[N.values];
    e=f=(*Q).data;
    while(a<=c&&b<=d)
    {
        f++;
        switch(comp(a->row,b->row))
        {
        case 1:
            *f=*a;
            a++;
            break;
        case 0:
            switch(comp(a->col,b->col))
            {
            case 1:
                *f=*a;
                a++;
                break;
            case 0:
                *f=*a;
                f->value+=b->value;
                if(!f->value)
                    f--;
                a++;
                b++;
                break;
            case-1:
                *f=*b;
                b++;
            }
            break;
        case-1:
            *f=*b;
            b++;
        }
    }
    if(a>c)
        while(b<=d)
        {
            f++;
            *f=*b;
            b++;
        }
        if(b>d)
            while(a<=c)
        {
            f++;
            *f=*a;
            a++;
        }
    (*Q).values=f-e;
    return 1;
}
void show(Matrix p)
{
    int i;
    for(i=1; i<=p.values; i++)
    {
        printf("%d %d %d\n",p.data[i].row,p.data[i].col,p.data[i].value);
    }
}
int main()
{
    Matrix A,B,C;
    Creat(&A);
    Copy(A,&B);
    Delete(&B);
    Creat(&B);
    printf("The transformed matrix is:\n");
    Transformed(A,&C);
    show(C);
    Add(A,B,&C);
    printf("The added matrix is:\n");
    show(C);
    return 0;
}

13. 计算二叉树叶子节点的数目

二叉树采用链式储存结构,设计算法计算一颗给定的二叉树中叶子节点的数目
1、使用递归创建并初始化二叉树。当输入的数据不为“#”时,将该元素视为一个有效的元素,否则置为null。每次递归返回当前位置的子树。

2、计算二叉树的所有叶子节点的数量。当一个节点的左孩子和右孩子都为空时。他是叶子节点。使用递归如果能找到就返回1,如果节点为NULL返回0,否则返回count(t->lchild)+ count(t->rchild)

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

typedef struct node
{
    char data ;
    struct node *leftchild;
    struct node *rightchild;
} BiTree;


BiTree *CreatTree()
{

    BiTree *t;
    char ch ;
    ch = getchar();
    if (ch != '#')
    {
        t=(BiTree *)malloc(sizeof(BiTree));
        t->data = ch ;
        t->leftchild = CreatTree();
        t->rightchild = CreatTree();
    }
    else
    {
        t=NULL;
    }
    return t;
}
int Count(BiTree *top)
{
    if(top == NULL)
    {
        return 0;
    }
    else if ((top->leftchild==NULL) && (top->rightchild==NULL))
    {
        return 1;
    }
    else
    {
        return Count(top->leftchild)+Count(top->rightchild);
    }
}

void Preorder(BiTree *top )
{
    if(top!=NULL)
    {
        printf("%c",top->data);
        Preorder(top->leftchild);
        Preorder(top->rightchild);
    }
}

int main()
{
    BiTree * top = NULL;
    top = CreatTree();
    printf("遍历:");
    Preorder(top);
    putchar('\n');
    printf("叶子数:%d\n",Count(top));

    return 0;
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值