【数据结构】从0开始数据结构学习-实验ITC平台部分题解

本节为ITC部分题解,回到总目录:点击此处

静态链表
#include <stdio.h>  
#include <string.h>  
   
#define MAXSIZE 11                        // 静态链表的长度  
typedef char ElemType[8];        // 元素的类型,规定姓氏不超过7个字符  
   
typedef struct  
{  
    ElemType data;                        // 节点中的数据  
    int cur;                                // 下一个节点的下标(相当于指针)  
} NodeType;                                       // 节点类型  
   
NodeType space[MAXSIZE];        // 用来存储节点的数组,相当于一般链表中的内存,  
// 只是那个内存是系统分配的,我们看不到  
   
typedef struct  
{  
    int elem;                                // 静态链表存储空间基址(起始元素的下标)  
    int length;                                // 静态链表中的元素数目  
    int listSize;                        // 静态链表当前的长度,可容纳元素数目  
} SLinkList;                                       // 静态链表类型的定义,和一般的链表类似  
   
int LocateElem_SL(SLinkList& S, ElemType e)  
{  
    // 在静态单链线性表L中查找第1个值为e的元素。  
    // 若找到,则返回它在L中的位序,否则返回0。  
    int i;  
    i = S.elem; // i指示表中第一个结点  
    while (i && strcmp(space[i].data, e))  
        i = space[i].cur; // 在表中顺链查找  
    return i;  
}  
   
void InitSpace_SL()  
{  
    // 将一维数组space中各分量链成一个备用链表,space[0].cur为头指针,  
    // "0"表示空指针  
    memset(space, 0 ,sizeof(space));  
    for (int i = 0; i < MAXSIZE - 1; ++i)  
        space[i].cur = i + 1;  
    space[MAXSIZE - 1].cur = 0;  
}  
   
int Malloc_SL()  
{  
    /* 若备用链表非空,则返回分配的结点下标(备用链表的第一个结点),否则返回0 */  
    int i = space[0].cur;  
    if (i) /* 备用链表非空 */  
        space[0].cur = space[i].cur;/* 备用链表的头结点指向原备用链表的第二个结点 */  
    return i;/* 返回新开辟结点的坐标 */  
}  
   
void Free_SL(int k)  
{/* 将下标为k的空闲结点回收到备用链表(成为备用链表的第一个结点) */  
    space[k].cur = space[0].cur;/* 回收结点的"游标"指向备用链表的第一个结点 */  
    space[0].cur = k; /* 备用链表的头结点指向新回收的结点 */  
}  
   
void Insert_SL(SLinkList& S, int i, ElemType e)  
{  
    // 往静态链表S中的第 i 个位置前插入e  
    int cur = S.elem;                // 指向静态链表中的第一个节点  
    int j=0;  
    int newNodeIndex;                // 存储新分配的节点下标  
    while(j < i-1)                         // 寻找第 i-1 个节点  
    {  
        cur = space[cur].cur;  
        ++j;  
    }  
    newNodeIndex = Malloc_SL();        // 分配新的节点  
    strcpy(space[newNodeIndex].data,e);        // 在新的节点中存入数据  
    space[newNodeIndex].cur = 0;                // 指针为空,这一点很重要  
    space[newNodeIndex].cur = space[cur].cur;        // 插入静态链表中  
    space[cur].cur = newNodeIndex;  
    S.length++;                        // 插入后静态链表长度加1  
}  
   
void Delete_SL(SLinkList& S, int i)  
{  
    // 删除静态链表中的第 i 个节点  
    int cur = S.elem;                // 指向静态链表中的第一个节点  
    int j=0;  
    int delCur;                                // 存储待删除节点的下标  
    while(j < i-1)                         // 寻找第 i-1 个节点  
    {  
        cur = space[cur].cur;  
        ++j;  
    }  
    delCur = space[cur].cur;                // 找到待删除节点的下标  
    space[cur].cur = space[delCur].cur;        // 删除节点  
    Free_SL(delCur);                        // 释放节点  
    S.length--;                        // 删除后静态链表长度减1  
}  
   
void CreateList_SL(SLinkList& S)         // 创建静态链表  
{  
    S.elem = Malloc_SL();                        // 分配头结点的指针  
    space[S.elem].cur = 0;  
    S.length = 0;  
    S.listSize = 9;  
}  
   
void Show_space()  
{  
    // 将静态链表中所有的节点显示出来  
    int i;  
    for(i=0; i<MAXSIZE; i++)  
    {  
        printf("%-8s%2d\n", space[i].data, space[i].cur);  
    }  
}  
   
int main()  
{  
   
    SLinkList S;                // 定义静态链表  
    char str[10];                // 用来获得指令  
    int a;                                // 存储位置  
    ElemType e;                        // 存储元素  
    InitSpace_SL();                // 初始化备用链表  
    CreateList_SL(S);        // 创建静态链表  
    while(scanf("%s", str) != EOF)  
    {  
        if(strcmp(str, "insert") == 0)                         // 插入元素  
        {  
            scanf("%d%s", &a, e);  
            Insert_SL(S, a, e);  
        }  
        else if(strcmp(str, "delete") == 0)          // 删除元素  
        {  
            scanf("%d", &a);  
            Delete_SL(S, a);  
        }  
        else if(strcmp(str, "search") == 0)          // 搜索元素  
        {  
            scanf("%s", e);  
            printf("%2d\n********************\n", LocateElem_SL(S, e));  
        }  
        else if(strcmp(str, "show") == 0)                  // 显示静态链表状态  
        {  
            Show_space();  
            puts("********************");                                                // 注意空一行  
        }  
    }  
    return 0;  
}
单链表的数据排序
void sort02(Linklist &L) //选择排序
{
    Node *r,*p;
    p = L -> next;
    while (p -> next != NULL)
    {
        r = p -> next;
        while (r != NULL)
        {
            if (p -> data > r -> data)
            {
                int t = p -> data;
                p -> data = r -> data;
                r -> data = t;
            }
            r = r -> next;
        }
        p = p -> next;
    }
}
void Bubble_sort(Linklist &L) //冒泡排序
{
    Node *cur,*tail;
    tail = L -> next;
    cur = L -> next;
    while (tail != NULL) //找到尾节点
    {
        tail = tail -> next;
    }
    while (cur != tail) //双层循环,冒泡排序
    {
        while(cur -> next != tail)
        {
            if(cur -> data > cur -> next -> data)
            {
                int t = cur-> data;
                cur -> data = cur -> next -> data;
                cur-> next -> data = t;
            }
            cur = cur -> next;
        }
        tail = cur;
        cur = L -> next;
    }
}
双向循环链表
DLinklist CreateList()
{
    DLinklist L;
    int num;
    L = (DNode *)malloc(sizeof(DNode));
    L -> next = L;
    L -> pre = L;
    DNode *p,*s;
    p = L;
    cin >> num;
    while (num != 0)
    {
        s = (DNode *)malloc(sizeof(DNode));
        s -> pre = NULL;
        s -> next = NULL;
        s -> data = num;
        p -> next = s;
        s -> pre = p;
        p = s;
        cin >> num;
    }
    p -> next = L;
    L -> pre = p;
    return L;
}
void sort04(DLinklist &L)
{
    DLinklist tmp = L->next,p = NULL,q = NULL;
    //将链表置空
    L->next = L;
    L->pre = L;
    while(tmp!=L){
        //保存原链表中tmp的下一个节点
        q = tmp->next;
        //找到tmp插入的位置
        for(p=L->pre;p!=L&&p->data>tmp->data;p=p->pre);
        //将tmp插入到p之后
        tmp->pre = p;
        tmp->next = p->next;
        p->next->pre = tmp;
        p->next = tmp;
        //将tmp指向要插入的下一个节点
        tmp = q;
    }
}
void sort02(DLinklist &L) //排序
{
    DNode *r,*p;
    DNode *head;
    head = L;
    p = L -> next;
    while (p -> next != head)
    {
        r = p -> next;
        while (r != head)
        {
            if (p -> data > r -> data)
            {
                int t = p -> data;
                p -> data = r -> data;
                r -> data = t;
            }
            r = r -> next;
        }
        p = p -> next;
    }
}
表达式求值(带小数、带括号)
#include <iostream>
#include <cmath>
#include <cstdio>
#define MaxSize 1000
using namespace std;

typedef struct Stack
{
    char ops[MaxSize];
    int top;
}SeqStack;

typedef struct Stack02
{
    double ops[MaxSize];
    int top;
}SeqStack02;

template <class T>
void InitStack(T &S) //栈的初始化
{
    S.top = -1;
}

template <class T, class P>
int Push(T &S, P ch) //进栈
{
    S.top ++;
    S.ops[S.top] = ch;
    return true;
}

template <class T, class P>  //出栈操作,取引用/以及函数取指针地址
int Pop(T &S, P *ch) //出栈
{
    if (S.top == -1) return false;
    else
    {
        *ch = S.ops[S.top];
        S.top--;
        return true;
    }
}

bool checknumber(char ch) //判断是数还是运算符
{
    switch(ch)
    {
    case '+':
    case '-':
    case '/':
    case '*':
    case '(':
    case ')':
    case '#':
        return true;
        break;
    default:
        return false;
        break;
    }
    return false;
}

template <class T>
char Gettop(T &S) //获取栈顶元素
{
    return S.ops[S.top];
}

char Compareoptr(SeqStack &S, char optr) //判断运算符的优先级
{
    if(Gettop(S)=='+'||Gettop(S)=='-')
    {
        if(optr=='+'||optr=='-'||optr=='>'||optr=='#'||optr==')'||optr==']')
            return '>';
        else return '<';
    }
    if(Gettop(S)=='*'||Gettop(S)=='/'){
        if(optr=='('||optr=='[')
            return '<';
        else return '>';
    }
    if(Gettop(S)=='('){
        if(optr==')')
            return '=';
        else return '<';
    }
    if(Gettop(S)=='['){
        if(optr==']')
            return '=';
        else return '<';
    }
    if(Gettop(S)=='#'){
        if(optr=='#')
            return '=';
        else return '<';
    }
    return '=';
}
template <class T, class P>
T calculate(T b,P op,T a)
{
    if (op == '+') return a + b;
    if (op == '-') return a - b;
    if (op == '*') return a * b;
    if (op == '/') return a / b;
    if (op == '#') return 0;
    return 0;
}

int main()
{
    char ch[MaxSize];
    while(cin >> ch)
    {
    	SeqStack OPTR;
    	SeqStack02 OVS;
    	double a = 0,b = 0;
    	double v = 0;
    	char x = '#';
    	InitStack(OPTR);
    	InitStack(OVS);
    	Push(OPTR,x);
    	int i = 0;
    	while (ch[i] != '#' || Gettop(OPTR) != '#')
    	{
        	if (!checknumber(ch[i]))
        	{
            	double q = 0;
            	double p = 0;
            	while (!checknumber(ch[i]))
            	{
             	   if(ch[i] >= '0' && ch[i] <= '9')
             	   {
             	       ch[i] = ch[i] - '0';
            	        q = q*10 + ch[i];
            	        i ++;
              	   }
               		if (ch[i] == '.')
                	{
                    	int j = 0;
                    	i ++;
                    	while (!checknumber(ch[i]))
                    	{
                        	ch[i] = ch[i] - '0';
                        	p = p*10 + ch[i];
                        	i ++;
                        	j ++;
                    	}
                    	p=pow(0.1,j)*p; //pow(x,y) x的y次方
                    	q=q+p;
                	}
            	}
            	Push(OVS,q);
        	}
        	else
        	{
            	switch(Compareoptr(OPTR,ch[i]))
            	{
                	case '<':
                    	Push(OPTR,ch[i]);
                    	i++;
                    break;
                	case '=':
                    	Pop(OPTR,&x);
                    	i++;
                    break;
                	case '>':
                    	Pop(OPTR,&x);
                    	Pop(OVS,&a);
                    	Pop(OVS,&b);
                    	v = calculate(a,x,b);
                    	Push(OVS,v);
                    break;
           		}
        	}
        }
        printf("%.2f\n",OVS.ops[OVS.top]);
    }
    return 0;
}
公共钥匙盒(模拟+优先队列)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>


using namespace std;

//优先队列解法

//核心:模拟+优先队列!
int key[1050];
struct node
{
    int num, sta, last;
    friend bool operator <(node a, node b)
    {
        if(a.sta==b.sta)
        {
        if(a.last==-1&&b.last!=-1)//-1代表要放回,b的优先级高
        return false;
        else if(a.last!=-1&&b.last==-1)
                return true;
        else
                return a.num > b.num;
        }
        return a.sta > b.sta;
    }
};

int main()
{
    int n, k, w, s, c;
    scanf("%d%d", &n, &k);
    memset(key, 0, sizeof(key));
    priority_queue<node> que;
    node temp;
    for(int i=0; i<k; i++)
    {
        scanf("%d%d%d", &w, &s, &c);
        temp.num = w;
        temp.sta = s;
        temp.last = c;
        que.push(temp);
    }
    for(int i=1; i<=n; i++)
        key[i] = i;
        while(!que.empty())
        {
            node r = que.top();
            que.pop();
            if(r.last==-1)//如果是放操作
            {
              for(int i=1; i<=n; i++)
              {
                  if(!key[i])
                   {
                       key[i] = r.num;break;
                   }
              }
            }
            else //是取操作
            {
                node r1 = r;
                r1.sta = r.sta+r.last;
                r1.last = -1;
                que.push(r1);
                for(int i=1; i<=n; i++)
                {
                    if(key[i]==r1.num)
                    {
                        key[i] = 0;
                        break;
                    }
                }
            }
        }
        for(int i=1; i<=n; i++)
        {
            cout << key[i] << " ";
        }
        cout << endl;
    return 0;
}
using namespace std;

typedef struct QNode
{
    int key;
    int start;
    int leave;
    struct QNode *next;
}QNode,*QueuePtr;

typedef struct
{
    QueuePtr front,rear;
}LinkQueue;

int InitQueue(LinkQueue *Q)
{
    Q -> front = Q -> rear = (QueuePtr)malloc(sizeof(QNode));
    if(!Q->front||!Q->rear)
    {
        return 0;
    }
    Q -> front -> next = NULL; //队头结点指向NULL
    return 1;
}

//判断是否为空
int QueueEmpty(LinkQueue Q)
{
    if(Q.front == Q.rear)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int QueueLen(LinkQueue Q)
{
    int i = 0;
    QueuePtr p;
    p = Q.front;
    while(p != Q.rear)
    {
        i ++;
        p = p -> next;
    }
    return i;
}

int QueuePush(LinkQueue *Q, int ek,int es,int el)
{
    QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
    if(!s)
    {
        return 0;
    }
    s -> key = ek;
    s -> start = es;
    s -> leave = el;
    s -> next = NULL;
    Q -> rear -> next = s;
    Q -> rear = s;
    return 1;
}

int QueuePop(LinkQueue *Q)
{
    QueuePtr p;
    if (Q -> front == Q -> rear)
    {
        return 0;
    }
    p = Q -> front -> next;
    Q -> front -> next = p -> next;
    if(Q->rear == p)
    {
        Q -> rear = Q -> front;
    }
    free(p);
    return 1;
}

int QueueTravel(LinkQueue Q)
{
    QueuePtr p;
    p = Q.front->next;
    while(p)
    {
        cout << p->key << " " << p->start << " " << p->leave << " " << endl;
        p = p -> next;
    }
    return 1;
}


void doubleswap(int q[][3],int s,int l)
{
    int dkey = q[s][0];
    int dstart = q[s][1];
    int dleave = q[s][2];
    q[s][0] = q[l][0];
    q[s][1] = q[l][1];
    q[s][2] = q[l][2];
    q[l][0] = dkey;
    q[l][1] = dstart;
    q[l][2] = dleave;
}

const int MAX = 10010;
int main()
{
    int N,K;
    int w,s,c;
    int data[MAX][3];
    int p = 0;
    int key[MAX];
    int maxtime = 0;
    int wait[MAX] = {0};
    cin >> N >> K;
    while (K --)
    {
        cin >> w >> s >> c;
        data[p][0] = w;
        data[p][1] = s;
        data[p][2] = c;
        p ++;
        maxtime = max(maxtime,s + c);
    }

    for (int i = 0; i < p; i ++)
    {
        cout << data[i][0] << " " << data[i][1] << " " << data[i][2] <<endl;
    }  √DEBUG完成!
    */
    /*DEBUG
    */
/*
    LinkQueue Q;
    InitQueue(&Q);//注意如何去初始化 指针类型去取引用!!!

    for (int i = 0; i < p; i ++)
    {
        QueuePush(&Q,data[i][0],data[i][1],data[i][2]);
    }
    //QueueTravel(Q);
    //DEBUG遍历一下队列 看看有没有问题
    DEBUG 链队列的操作
    QueuePush(&Q,4,3,3);
    QueuePush(&Q,2,2,7);
    QueueTravel(Q);
    */
    //cout << Q->front->key << " "<<Q ->front->start << " " << Q->front->leave << " "<< endl;


/*
    //处理算法 !!! 反思自己写得模拟算法速度太慢了!!处理数据过多就会出问题!!
    QueuePtr pp = Q.front;
    pp = pp -> next;
    for (int i = 1; i <= maxtime; i ++)
    {
        for(int j = 0; j <= N; j++) //还钥匙以及等待时间置为0
        {
            if(i == wait[j])
            {
                wait[j] = 0; //将j门的钥匙的等待时间置为0
                for(int p = 1; p <= N; p ++) //然后把钥匙放回去
                {
                    if(key[p] == 0)
                    {
                        key[p] = j; //= 和 ==一定要注意别粗心写错了~
                        break;
                    }
                }
            }
        }
        if((i == pp->start) && (wait[pp -> key] == 0) ) //拿钥匙 √
        {
            for(int ke = 1; ke <= N ;ke ++)
            {
                if(key[ke] == pp -> key)
                {
                    key[ke] = 0;
                    break;
                }
            } //拿钥匙
            wait[pp->key] = pp->start + pp->leave;
            if (pp != Q.rear) //注意增加遍历的判断条件
            {
                pp = pp -> next;
            }
            //pp = pp -> next; //DEBUG
        }
    }
    //输出结果 //完成辽
    for (int i = 1; i <= N; i ++)
    {
        cout << key[i] << " ";
    }
    return 0;
}
//题后心得:
//1.链队列的创建,使用和进行操作应该掌握再熟练一点,切忌一知半解!!!
//2.链队列的运用函数时候,如果是指针类型,传入函数应该加上引用!!以免出错!!因为是同一个指针!
//3.模拟算法应该想办法更加优化一下,降低时间复杂度!
*/
找最长公共子串KMP的应用其一
//最长公共子串 KMP的应用
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>

using namespace std;

void GetNext(vector<char> ptr, int next[])
{
    next[0] = -1;
    int k = -1;
    unsigned int i = 1; //一定要注意这里是从 1开始 不是从0开始哒!
    while (i <= ptr.size() - 1)
    {
        while (k > -1 && ptr[k + 1] != ptr[i])
        {
            k = next[k];
        }
        if (ptr[k + 1] == ptr[i])
        {
            k ++;
        }
        next[i] = k;
        i ++;
    }
}

bool KMP(vector<char> str, vector<char> ptr)
{
    int *next = new int[ptr.size()];
    GetNext(ptr,next);
    /* DEBUG
    cout << "**************" << endl;
    for (unsigned int p = 0; p < ptr.size(); p ++) cout << next[p] << " ";
    cout << endl;
    cout << "**************" << endl;
    */
    int k = -1;
    unsigned int i = 0;
    while (i <= str.size() - 1)
    {
        while (k > -1 && str[i] != ptr[k + 1])
        {
            k = next[k];
        }
        if (str[i] == ptr[k + 1])
        {
            k ++;
        }
        if (k == (int)ptr.size() - 1)
        {
            return true;
        }
        i++;
    }
    return false;
}

//DEBUG
int Getstrspace(string s)
{
    int i = 0;
    while (s[i] != ' ' && i < (int)s.length() - 1)
    {
        i ++;
    }
    return i;
}

int main()
{
    string str;
    string ptr;
    cin >> str;
    cin >> ptr;
    vector<char> sstr;
    for (int i = 0; i < (int)str.size(); i++) sstr.push_back(str[i]);
    vector<char> res;
    int t = 0;
    //参考:https://blog.csdn.net/qq_46527915/article/details/109655758
    //DEBUG
    /*DEBUG检查一下KMP算法是否有效
    vector<char> pptr;
    for (int i = 0; i < (int)ptr.size(); i++) pptr.push_back(ptr[i]);
    int ress = KMP(sstr,pptr);
    cout << ress;
    */

    //暴力算法
    int maxLen = 0;
    vector<char> max_res;
    for (int k = ptr.length(); k >= 1; k --) //获取全部子串
    {
        for (int i = 1; i <= k; i ++)
        {
            for (int j = 1; j <= i; j ++) //三重循环把模式串中的所有子串都取出来,然后使用KMP算法判断是否匹配
            {
                res.push_back(ptr[j -1 + t]);
            }
            int k = KMP(sstr,res);
            if (k)
            {
                if ((int)res.size() > maxLen)
                {
                    maxLen = max(maxLen,(int)res.size());
                    while (!max_res.empty())
                    {
                        max_res.pop_back();
                    }
                    for (int i = 0; i < (int)res.size(); i ++)
                    {
                        max_res.push_back(res[i]);
                    }
                }
            }
            while(!res.empty())
            {
                res.pop_back();
            }
        }
        t ++;
    }
    for(int i = 0; i < (int)max_res.size(); i ++)
    {
        cout << max_res[i];
    }
    return 0;
}
二叉树创建及遍历

给出一个按照先序遍历得出的字符串,‘#’ 代表空的子节点,大写字母代表节点内容。请通过这个字符串建立二叉树,并分别采用“递归”和“非递归”的先序、中序、后序遍历的算法分别输出每一个非空节点。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;

typedef struct BitNode
{
    char data;
    struct BitNode *Lchild,*Rchild;
}BitNode,*BitTree;

//后续遍历增加一个tag标签
typedef struct SNode
{
    BitTree p;
    int tag;
}SNode;

int top = -1;
//先序创建
void CreateTree(BitTree *bt)
{
    char ch;
    ch = getchar();
    if(ch=='#')
    {
        *bt = NULL;
    }
    else
    {
        *bt = (BitTree)malloc(sizeof(BitNode));
        (*bt) -> data = ch;
        CreateTree(&((*bt) -> Lchild));
        CreateTree(&((*bt) -> Rchild));
    }
}

//先序遍历(递归)
void PreOrder(BitTree root)
{
    if(root)
    {
        cout << root->data << " ";
        PreOrder(root->Lchild);
        PreOrder(root->Rchild);
    }
}
//中序遍历(递归)
void InOrder(BitTree root)
{
    if(root)
    {
        InOrder(root->Lchild);
        cout << root->data << " ";
        InOrder(root->Rchild);
    }
}
//后序遍历(递归)
void BackOrder(BitTree root)
{
    if(root)
    {
        BackOrder(root->Lchild);
        BackOrder(root->Rchild);
        cout << root->data << " ";
    }
}

//非递归实现//
//预备函数//栈
BitNode *gettop(BitNode **a)
{
    return a[top];
}
void display(BitNode *e)
{
    cout << e -> data << " ";
}
void pop()
{
    if(top == -1)
    {
        return;
    }
    top --;
}
void push(BitNode** a,BitNode *e)
{
    a[++top]=e;
}



//先序遍历非递归方法
void PreOrderStack(BitTree bt)
{
    BitNode* a[100];
    BitNode *p;
    push(a,bt);
    while(top != -1)
    {
        p = gettop(a);
        pop();
        while(p)
        {
            display(p);
            if(p -> Rchild)
            {
                push(a,p->Rchild);
            }
            p = p -> Lchild;
        }
    }
}
//中序遍历非递归方法
void InOrderStack(BitTree bt)
{
    BitNode* a[100];
    BitNode *p;
    push(a,bt);
    while(top != -1)
    {
        while((p = gettop(a)) && p)
        {
            push(a,p -> Lchild);
        }
        pop();
        if(top!= -1)
        {
            p = gettop(a);
            pop();
            display(p);
            push(a,p -> Rchild);
        }
    }
}
//后续遍历非递归算法
void Postpush(SNode *a,SNode sdata)
{
    a[++top] = sdata;
}
void PostOrderStack(BitTree bt)
{
    SNode a[100];
    BitNode *p;
    int tag;
    SNode sdata;
    p = bt;
    while(p || top != -1)
    {
        while(p)
        {
            sdata.p = p;
            sdata.tag = 0;
            Postpush(a,sdata);
            p = p -> Lchild;
        }
        sdata = a[top];
        pop();
        p = sdata.p;
        tag = sdata.tag;
        if(tag == 0)
        {
            sdata.p = p;
            sdata.tag = 1;
            Postpush(a,sdata);
            p = p -> Rchild;
        }
        else
        {
            display(p);
            p = NULL;
        }
    }
}


int main()
{
    BitTree bt;
    CreateTree(&bt);
    PreOrder(bt);
    cout << endl;
    InOrder(bt);
    cout << endl;
    BackOrder(bt);
    cout << endl;
    PreOrderStack(bt);
    cout << endl;
    InOrderStack(bt);
    cout << endl;
    PostOrderStack(bt);
    return 0;
}
二叉树根据中序和后序求前序遍历
#include <bits/stdc++.h>
using namespace std;

string in,post;

typedef struct BiNode
{
    char data;
    struct BiNode *Lchild,*Rchild;
}BiNode,*BiTree;

BiTree Create(int LPost, int RPost,int Lin, int Rin)
{
    if (LPost > RPost) return NULL;
    BiNode *root = (BiNode*)malloc(sizeof(BiNode));
    root -> data = post[RPost];
    int k;
    for (k = Lin;k < int(in.length()); k ++)
    {
        if (in[k]==post[RPost]) break;
    }
    int num = k - Lin;
    root -> Lchild = Create(LPost,LPost+num-1,Lin,k-1);
    root -> Rchild = Create(LPost+num,RPost-1,k+1,Rin);
    return root;
}

void preOrder(BiTree root)
{
    if (root == NULL)
        return;
    cout << root->data;
    preOrder(root->Lchild);
    preOrder(root->Rchild);
}

int main()
{
    cin >> in;
    cin >> post;
    int Rin = in.length() - 1;
    int RPost = post.length() - 1;
    BiTree bt = Create(0,Rin,0,RPost);
    preOrder(bt);
    return 0;
}
二叉树结点的共同祖先问题 (也包含根据前序和中序获取二叉树)
#include <bits/stdc++.h>

using namespace std;

typedef struct BiNode
{
    char data;
    struct BiNode *Lchild,*Rchild;
}BiNode,*BiTree;

//依据前序和中序求出二叉树
BiTree Create(char *pre,char *in,int len)
{
    if (len == 0) return NULL; //如果长度为0则为空结点,直接返回
    BiNode *p;
    p = (BiNode*)malloc(sizeof(BiNode));
    p -> data = pre[0]; //存放根结点
    int i;
    for(i = 0;i < len; i++)
    {
        if(pre[0] == in[i]) break;
    }
    p -> Lchild = Create(pre+1,in,i);
    p -> Rchild = Create(pre+i+1,in+i+1,len-i-1);
    return p;
}

BiNode* Trave(BiTree bt, BiNode *node1, BiNode *node2)
{
    if(bt == NULL) return NULL;
    if(bt -> data == node1 -> data ||bt -> data == node2 -> data) return bt;
    BiNode *L = Trave(bt -> Lchild,node1,node2);
    BiNode *R = Trave(bt -> Rchild,node1,node2);
    if(L!=NULL&&R!=NULL) return bt;
    if(L) return L;
    if(R) return R;
    return NULL;
}
/*
void Search(BiNode *bt,BiNode *node)
{
    if(bt)
    {
        if(bt->data==node->data)
        {
            node =bt;
            Search(bt->Lchild,node);
            Search(bt->Rchild,node);
        }
    }
}
*/
BiNode *GetPa(BiNode *bt,BiNode *node1,BiNode *node2)
{
    BiNode *p = Trave(bt,node1,node2);
    return p;
}
int main()
{
    BiNode *bt,*node1,*node2,*node;
    node = (BiNode*)malloc(sizeof(BiNode));
    node1 = (BiNode*)malloc(sizeof(BiNode));
    node2 = (BiNode*)malloc(sizeof(BiNode));
    char pre[50],in[50];
    cin >> pre >> in;
    int len = strlen(pre);
    bt = Create(pre,in,len);
    char num1,num2;
    cin >> num1 >> num2;
    node1 -> data = num1;
    node2 -> data = num2;
    //Search(bt,node1);
    //Search(bt,node2);
    node = GetPa(bt,node1,node2);
    if(node != NULL && node -> data != bt -> data) printf("%c",node->data);
    else printf("NULL");
    return 0;
}
二叉树左右子树交换操作 (递归实现)并用后序输出
#include <bits/stdc++.h>

using namespace std;

typedef struct BiNode
{
    char data;
    struct BiNode *Lchild,*Rchild;
}BiNode,*BiTree;

void CreateTree(BiTree *bt)
{
    char ch;
    ch = getchar();
    if(ch == '#')
    {
        *bt = NULL;
    }
    else
    {
        *bt = (BiNode *)malloc(sizeof(BiNode));
        (*bt) -> data = ch;
        CreateTree(&((*bt) -> Lchild));
        CreateTree(&((*bt) -> Rchild));
    }
}
//计数叶子结点
int LeafCount(BiTree bt)
{
    int count;
    if (bt == NULL) return 0;
    else if((bt -> Lchild == NULL) && (bt -> Rchild == NULL)) return 1;
    else
    {
        count = LeafCount(bt -> Lchild) + LeafCount((bt -> Rchild));
    }
    return count;
}

void PostTraverse(BiTree bt)
{
    if(bt)
    {
        PostTraverse(bt -> Lchild);
        PostTraverse(bt -> Rchild);
        cout << bt -> data;
    }
    else cout << "#";
}
//用于交换左右子树
void SwapIntial(BiNode *&R,BiNode *&L)
{
    BiNode *t = R;
    R = L;
    L = t;
}
//递归【分治】完成左右子树的交换
void Exchange(BiTree bt)
{
    if (bt)
    {
        Exchange(bt -> Rchild);
        Exchange(bt -> Lchild);
        SwapIntial(bt -> Rchild,bt -> Lchild);
    }
}

int main()
{
    BiTree bt;
    int countnum;
    CreateTree(&bt);
    countnum = LeafCount(bt);
    cout << countnum <<endl;
    Exchange(bt);
    PostTraverse(bt);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值