1.5PTA training 6-1~6-4, 7-3, 7-4 (6/26)

6-1 Deletion score of sequence table 10

List Delete( List &L, ElementType minD, ElementType maxD ){
    int k=0;
    for(int i=0;i<=L.last;i++){
        if(L.Data[i]<=maxD&&L.Data[i]>=minD){
            L.Data[k++]=L.Data[i];
        }
    }
    L.last=k;
    return L;
}

This is to note that L needs to be used., not ->, not arrows. I don’t know why specifically.

The idea is to perform operations on the original table, then if the conditions are met, add it to the new array, and finally update the length of the new array. 

6-2 Find the predecessor node score of the linked list element 10

ptr pre (ptr h,int x){
    if(!h)return nullptr;//为空,则直接返回
    node* pre=h,*cur=h->next;//不为空的话,则pre一定存在,cur可能一开始就不存在,cur表示要操作的结点,pre表示接收的结点,也可理解为操作完成的结点
    while(cur){//这个迭代条件,就意味着还能继续操作,为空时就是不能继续操作了
        if(cur->data==x){//此时就表示满足要求了,就不需要操作了,找到了,直接返回
            return pre;
        }else{//就是还没找到,继续找
            pre=cur;
            cur=cur->next;
        }//同时向后移动
    }
    return nullptr;//出了循环,就意味着没有可以继续操作的结点,就意味着没找到,就是说不存在,返回空指针
}

The idea of ​​​​the linked list question is relatively fixed, that is, a pointer points to the node to be operated (cur), and a judgment statement is used to determine whether the current node meets the requirements or operation requirements, and the other node receives the result of the operation.

6-3 Find the number of leaf nodes and score 50

using namespace std;
#include<iostream>
void creat(BiTree &Tree){//创建二叉树
    char t;
    cin>>t;
    if(t=='#'){
        Tree=nullptr;
    }else{
        //Tree =new BiTNode;
        Tree->data=t;
        creat(Tree->lchild);
        creat(Tree->rchild);
    }
}
int countleaf(BiTree Tree){//叶子结点计数
    if(!Tree)return 0;
    if(!Tree->rchild&&!Tree->lchild)return 1;
    return countleaf(Tree->lchild)+countleaf(Tree->rchild);
}

As for the subject disintegration part, the idea is to determine whether it is a leaf node. If so, return 1. If not, return the sum of the left and right child leaf nodes.

Abstractly speaking, first determine whether it is empty or not. If it is empty, return directly. Then look at the operating conditions. If the bottom layer is satisfied, return. Otherwise, continue to recurse downward. 

Particular attention needs to be paid to the operation of building trees.

First of all, use &. When quoting, although the above question requires using ., you still need to use -> here, so if you get an error, please read it again.

Secondly, build a tree and create a new node. Even if it is a reference, it must be new and open a space in the heap area to store it. Otherwise, problems will occur. The guess is that if it is not new, the node will be passed down at this time. What is passed in is a null pointer, that is to say, there is no such thing as its left and right children, because it is a null pointer, which is equivalent to a null pointer when it is passed in. There is no index of the left and right children, only a new one. Only after that will the indexes of the left and right children exist

If it is void type, it needs to be quoted.

6-4 Find the height score of a binary tree 40

#include<iostream>
using namespace std;

void creat(BiTree &Tree){//构建二叉树
    char t;
    cin>>t;
    if(t=='#'){
        Tree=nullptr;
    }else{
        Tree=new BiTNode;
        Tree->data=t;
        creat(Tree->lchild);
        creat(Tree->rchild);
    }
}
int Depth(BiTree Tree){//求高度
    if(!Tree)return 0;
    else if(!Tree->lchild&&!Tree->rchild)return 1;
    else return max(Depth(Tree->lchild),Depth(Tree->rchild))+1;
}

Pay attention to the details, that is, function questions may not include #include<iostream> and using...

There is also a reference. You don’t need to add & when calling, just add it when writing the function definition.

The main idea of ​​solving the problem is to first judge whether it is empty, then judge whether it is a recursive bottom layer, and then make a recursive call to perform a series of operations. According to the recursive equation and the state transition equation

7-3 String matching problem (strs) score 100

From the inside to the outside it must be <,(,[,{, that is, { is the largest and must be at the outermost

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int n;
string s;
int main(){
    cin>>n;
    while(n--){
        cin>>s;
        stack<int>st;
        bool flag=1;
        for(int i=0;i<s.length();i++){
            if(s[i]=='{'){
                if(!st.empty()&&st.top()>1){
                    flag=0;
                    break;
                }else{
                    st.push(1);
                }
            }
            if(s[i]=='['){
                if(!st.empty()&&st.top()>2){
                    flag=0;
                    break;
                }else{
                    st.push(2);
                }
            }
            if(s[i]=='('){
                if(!st.empty()&&st.top()>3){
                    flag=0;
                    break;
                }else{
                    st.push(3);
                }
            }
            if(s[i]=='<'){
                st.push(4);
            }
            if(s[i]=='>'){
                if(st.empty()||st.top()!=4){
                    flag=0;
                    break;
                }else{
                    st.pop();
                }
            }
            if(s[i]==')'){
                if(st.empty()||st.top()!=3){
                    flag=0;
                    break;
                }else{
                    st.pop();
                }
            }
            if(s[i]==']'){
                if(st.empty()||st.top()!=2){
                    flag=0;
                    break;
                }else{
                    st.pop();
                }
            }
            if(s[i]=='}'){
                if(st.empty()||st.top()!=1){
                    flag=0;
                    break;
                }else{
                    st.pop();
                }
            }
        }
        if(flag&&st.empty()){
            cout<<"YES"<<endl;
        }else{
            cout<<"NO"<<endl;
        }
    }
    return 0;
}

When it is a left parenthesis, it is pushed onto the stack and when it is a right parenthesis, it is popped off the stack. 

Due to size limitations, when pushing into the stack, it is necessary to determine whether the top element of the stack is larger than itself. However, it should be noted that when removing the top element of the stack, it is necessary to first determine whether the stack is empty. The top of the stack can only be removed when it is not empty. element

When popping the stack, determine whether the stack is empty and whether the top element of the stack matches itself.

When pushing into the stack, it is judged whether it can be pushed into the stack, and when it is popped out of the stack, it is judged whether it can be pushed out of the stack. That's it.

In the final output, you don’t need to consider the failure situations, you only need to consider the correct situations.

This is to establish mapping, through map

    char a[] = { '{','[','(','<','}',']',')','>' };
    int b[300], n;
    cin >> n;
    while (n--) {
        string s;
        cin >> s;
        stack<int>st;
        bool flag = true;
        for (int i = 0; i < s.size(); i++) {
            for (int j = 0; j < 8; j++) {
                if (s[i] == a[j]) {
                    b[i] = j;
                    break;//就是把原来的括号字符串转换为B里的数字数组
                }
            }
        }
        for (int i = 0; i < s.size(); i++) {
            if (b[i] <= 3) {
                if (!st.empty() && b[i] < st.top()) {//用数字代表括号的优先次序,那么能不能继续插入,就是看堆顶的元素的编号和此时自己的关系
                    flag = false;//也就是必须要保证一个递增的顺序,不然就不能继续插入
                    break;
                }
                else {
                    st.push(b[i]);
                }//正常插入
            }
            else if (b[i] >= 4) {
                if (st.empty() || (st.top() + 4) != b[i]) {
                    flag = false;
                    break;
                }
                else {
                    st.pop();//正常的匹配,删除
                }
            }
        }
        if (!st.empty())cout << "no" << endl;
        else if (flag)cout << "yes" << endl;
        else cout << "no" << endl;
    }

7-4 Postfix expression evaluation fraction 20

First, pay attention to the string input. If there are spaces in the input string, it will be terminated early.

Direct cin string is only applicable when the input string does not contain spaces. If it contains spaces, you can only use the getline function to obtain getline(cin,s)

The next step is to process the input string

First the numbers,

First determine whether the first one is a number. If so, then use while and try to get all the numbers in China Unicom, which is a whole number. Pay attention to j++ during while.

It should also be noted that whether the currently input is a negative number depends on whether the character in front of the first number is a symbol. It should also be noted that when making this judgment, you must first ensure that there is a character in front of it, that is, i >0, otherwise it will be out of bounds; add the positive or negative number of the obtained number according to the previous character situation, and push it onto the stack, so that the number of elements in the stack is cnt++, and jump from the position i to j, the position jumped to at this time It happens to be a position that is not a number. It is the first position that breaks away from this position that is not a number.

But it should also be noted that it is not good to process it directly, that is, set it directly to the first position, because after the processing here, i++ will be performed later. The reason why there is no problem here is because all the spaces follow. Does not participate in the operation, otherwise, the first position is not a number, that is, the first position will not be processed. After the i loop ends, it will be skipped by i++, and the situation will be lost, so you still need to pay attention one time

Understanding of while iteration processing 

Whether it is in a linked list or here, when doing iterative loop processing while, the clearest way to understand the idea is whether it can continue to operate, that is, the conditions for continuing iteration. Here, j represents the character that is currently trying to continue processing. , if it satisfies while, it means that processing can continue, otherwise processing cannot continue.

Then use i to receive and num to receive

Here, if s[j]>="0"&&s[j]<="9" is satisfied, it means that the processing can continue, that is, the current number of digits is still a number. If it is not satisfied, it is j. is not a number, we will stop processing and keep the current number of digits unchanged. That is, after the while ends, the first number that does not satisfy the iteration condition will be saved.

The intermediate processing is to skip when encountering a space or a negative sign in front of a number (this negative sign means it is not an operator but a negative sign). 

The next step is to operate and process the operators. After an else, it means that all the operators will be processed next. It should be noted that it is precisely because of this else that in the termination condition of the for loop, what should be written is Not i<s.length()

Because if it is the latter, the == "#" situation is included in else, which will be considered an operator, so if cnt<2 at this time, Expression Error: will be output incorrectly, and # happens to be the last The terminator, so at the end, when it is correct, cnt should be exactly =1, so the correct output at this time will definitely be marked as wrong.

In other words, the way of writing this for actually excludes #, which is actually equivalent to i<s[i].length()-1;

Then cnt is the statistics of the number in the stack. If it is less than 2, it is an error condition and you can exit early . And if you do not exit at this time, an error will definitely be reported because there are no more than two numbers in the stack to support the operation. operator 

But one of the problems here is that cnt<2, there can be two situations, namely cnt=0=1. Here we only consider the case of =1, but the case of =0 is not considered, that is, the case of string The first element must not be an operator 

And this may also meet the requirements of the question, because it means that when cnt<2, the top element of the stack should be output at this time. If =0, it means that there is no top element of the stack at all, which is contradictory.

Next, when dealing with operators, you need to pay attention to subtraction and division. You need to consider the order issue, that is, find the right dividend, and additionally consider the issue of division by 0 in division. 

In addition, postfix expressions do not need to consider order issues, and there is no priority of operators. Operations are performed when encountering them. There is no need to first add, subtract, and then multiply and divide.

Finally, the processing is completed. If the processing is completed, there should be exactly one element in the stack. If it is not 1, it is an error.

If it is not 1 here, it can only be the case when there are many elements in the stack, that is, there are many numbers and few operators.

If there are many operators and few numbers, they will be processed when processing the string and returned early.

At this point, the string processing has been completed, but there may still be many numbers in the stack.

Supongo que te gusta

Origin blog.csdn.net/m0_73553411/article/details/135419233
Recomendado
Clasificación