LeetCode brush stack of title

Interview questions 03.04. Of the stack for the team

MyQueue implement a class that implemented a stack with two queues.
.
.
Example:
.
MyQueue MyQueue new new Queue = ();
.
Queue.push (. 1); queue.push (2); queue.peek (); // Returns 1 queue.pop (); //
Returns 1 queue. empty (); // returns false
.
Note:
.
you can only use the standard stack operations - that is, only the push to top, peek / pop from top, size is empty and
the operation is legal. The language you are using may not support stack. You can use the list or the deque (deque) to simulate a stack, as long as a standard stack operation can.
Assuming that all operations are valid (e.g., not an empty queue or peek operation called pop).
.
Source: stay button (LeetCode) "Golden programmer interview (Sixth Edition)"
Difficulty: Simple
link: https: //leetcode-cn.com/problems/implement-queue-using-stacks-lcci
copyright of the collar button Network all. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Idea: to delete queue one end (i.e., the team), the other end of the insertion (i.e., queued) data structure.
Questions asked two stack space, then we make a limit to only pop operation, only a push operation, imitating the team and the operations team queue.
pop stack we named frontStack, push the stack we named rearStack, the following code implementation has detailed notes.

#define MAXSIZE 30
#define OK 1
#define ERR 0

typedef struct Stack
{
    int top;
    int data[MAXSIZE];
}Stack, * StackPtr;

typedef struct {
    Stack* rearStack;
    Stack* frontStack; 
} MyQueue, * MyQueuePtr;

bool myQueueEmpty(MyQueue* obj);

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
    
    //初始化队列空间
    MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
    if (!obj)
        goto err1;
    memset(obj, 0, sizeof(MyQueue));

    //初始化push栈空间
    obj->rearStack = (Stack*)malloc(sizeof(Stack));
    if (!obj->rearStack)
        goto err2;
    memset(obj->rearStack, 0, sizeof(Stack));
    obj->rearStack->top = -1;

    //初始化pop栈空间
    obj->frontStack = (Stack*)malloc(sizeof(Stack));
    if (!obj->frontStack)
        goto err3;
    memset(obj->frontStack, 0, sizeof(Stack));
    obj->frontStack->top = -1;


    return obj;


    //集中处理malloc失败的情况。
err3:
    if (obj->frontStack)
        free(obj->frontStack);
err2:
    if (obj->rearStack)
        free(obj->rearStack);
err1:
    if (obj)
        free(obj);

    return NULL;
}

/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {   
        //判断是否队满
    if (obj->rearStack->top == MAXSIZE - 1)
        return;

    //将pop栈的数据转移到push栈,若没有则直接退出
    while (obj->frontStack->top != -1)
    {
        obj->rearStack->data[++obj->rearStack->top] = obj->frontStack->data[obj->frontStack->top--];
    }
    
    //将数据push
    obj->rearStack->data[++obj->rearStack->top] = x;
}

/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
    //判断队列是否为空
    if (myQueueEmpty(obj))
        return ERR;
    
    //将push栈的数据转移到pop栈,若没有则直接退出
    while (obj->rearStack->top != -1)
    {
        obj->frontStack->data[++obj->frontStack->top] = obj->rearStack->data[obj->rearStack->top--];
    }

    //pop出去,并返回。
    return obj->frontStack->data[obj->frontStack->top--];
}

/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
    if (myQueueEmpty(obj))
        return ERR;

    //判断现在数据在哪个栈空间。
    if (obj->frontStack->top == -1)
    {
        return obj->rearStack->data[0]; //在rear栈中,此时rear指向rear栈的top次,front指向0处
    }
    else
    {
        return obj->frontStack->data[obj->frontStack->top]; //front栈中,直接返回即可
    }
}

/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
    return (obj->frontStack->top == -1 && obj->rearStack->top == -1) ? true : false;
}

//逐一free内存
void myQueueFree(MyQueue* obj) {
    free(obj->frontStack);
    free(obj->rearStack);
    free(obj);
}


09. interview questions with two stacks queue

A queue is implemented with two stacks. The following statement queue, implement its two functions appendTail and deleteHead
, were completed at the end of the queue insert and delete integer integer in the head of the queue function. (If there is no queue element, deleteHead operation returns -1)

Source: stay button (LeetCode) "wins the offer (Second Edition)"
Difficulty: Simple
link: https: //leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie- lcof
the copyright collar button all the network. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Ideas: We define two stack space, rear and front, respectively, as one of the top of the stack pointer. We define a rear stack space is only push into the team, while the front only pop the stack is a team in order to use two stacks to mimic the queue.
The following code key areas were given a comment.

#define MAXSIZE 300
#define REAR 1
#define FRONT 0

typedef struct CQueue
{
    //设置2个数组,即2个栈空间,分别定义2个宏REAR,FRONT现性的指明。
	int data[2][MAXSIZE];
	int front, rear;
} CQueue;


CQueue* cQueueCreate() {
	
	CQueue* obj = (CQueue*)malloc(sizeof(CQueue));
	if (!obj)
		return NULL;
	memset(obj, 0, sizeof(CQueue));
	obj->rear = obj->front = -1;	//rear和front分别为一个栈空间的栈顶指针,初始化指向栈底。

	return obj;
}

void cQueueAppendTail(CQueue* obj, int value) {
	//判断是否满队
	if (obj->rear == MAXSIZE - 1 || obj->front == MAXSIZE - 1)
		return;

	//如果数据在front栈,则转移数据到rear栈中
	while (obj->front != -1)
	{
		obj->data[REAR][++obj->rear] = obj->data[FRONT][obj->front--];
	}
	obj->data[REAR][++obj->rear] = value;
}

int cQueueDeleteHead(CQueue* obj) {
	if (obj->rear == obj->front)
		return -1;

	//如果数据在rear栈,则转移数据到front栈中
	while (obj->rear != -1)
		obj->data[FRONT][++obj->front] = obj->data[REAR][obj->rear--];

	return obj->data[FRONT][obj->front--];
}

void cQueueFree(CQueue* obj) {
	free(obj);
}


1047. deletes all adjacent duplicate entries in a string

Editing in: March 2020 22:10:39 17

String S is given by the lowercase letters, delete duplicates and selects two identical letters adjacent to, and remove them.

Performed on the S repeatedly duplicates deletion, can not continue until deleted.

Returns the final string after the completion of all duplicates deletion. The only answer guarantee.

Example:

Enter: "abbaca" Output: "ca" interpretation: for example, in "abbaca", we can remove the "bb"
as the two adjacent letters and the same, this is the only duplicates this time can perform delete operations. After we get the string "aaca", which has only "aa"
can perform delete duplicates, so the final string is "ca".

prompt:

1 <= S.length <= 20000 S only by the lower case letters.

Source: stay button (LeetCode)
Difficulty: Simple
link: https: //leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

1 I initially thought the idea is very simple. Maintain a stack, continue to read data onto the stack, the stack data if there is a repeat of adjacent data stack.
Sentiment: but finished out a little dissatisfied, he saw a reminder of a big brother, epiphany. Feeling under the optimized code.
2 ideas: we can use the index to traverse always less than the top end of the stack as the target value S pointing to the nature of this memory space as a stack space.
The reason is simple beginning of stack space expansion and traverse speed is the same, but the way we will continue to push out of the stack, which makes the expansion of stack traversal speed can never exceed the speed.
The so-called traversal is a collection of all the elements are accessed again. That top can only manipulate the data we visited, but we can not do without operational data unvisited, so this does not affect the traversal.

//最初的版本
#define MAXSIZE 20000

char* removeDuplicates(char* S) {
    //设立栈
    int top = -1;
    char data[MAXSIZE] = { 0 };

    for (int i = 0; S[i]; i++)
    {
        //判断栈是否满。加1是为了预留'\0'字符
        if (top + 1 == MAXSIZE - 1)
            return NULL;

        data[++top] = S[i];     //字符串s字符逐一入栈
        if (top > 0 && data[top] == data[top - 1])  //查找是否有重复,若有出栈
            top -= 2;
        if(top >= 0)
            S[top] = data[top];
    }
    S[top + 1] = '\0';

    return S;
}

//优化后的C代码

char* removeDuplicates(char* S) {
    int top = 0;
    for (int read = 0; S[read]; read++, top++)
    {
        S[top] = S[read];     //字符串s字符逐一入栈
        if (top > 0 && S[top] == S[top - 1])  //查找是否有重复,若有出栈
            top -= 2;
    }
    S[top] = '\0';

    return S;
}

Published 19 original articles · won praise 2 · Views 2536

Guess you like

Origin blog.csdn.net/SC_king/article/details/104928462