數據結構代碼彙總

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章