MOOC 2.2 Stack

1. sequential storage

#include <cstdio> 
<the maximum number of storage elements> #define the MaxSize 
typedef struct SNODE * Stack; 
struct SNODE 
{ 
	the ElementType the Data [the MaxSize]; 
	int Top; 
}; 

// stack 1. 
void Push (Stack PtrS, ElementType item ) 
{ 
	IF (PtrS-> Top the MaxSize == -. 1) 
	{ 
		the printf ( "stack full"); 
		return; 
	} 
	the else 
	{ 
		PtrS-> the Data [++ (PtrS-> Top)] = Item; 
		return; 
	} 
} 

/ / 2. stack 
the ElementType Pop (stack PTRS) 
{ 
	IF (PtrS-> Top == -1) 
	{ 
		the printf ( "empty stack"); 
		return ERROR; 
	} 
	the else 
	{
		return (PtrS->Data[(PtrS->Top)--]);
	}
} 

  

Share Stack

// shared stack 
#define MaxSize <the maximum number of storage elements> 
struct DStack 
{ 
	the ElementType the Data [the MaxSize]; 
	int of Top1; 
	int Top2; 
} S; 

S.Top1 = -1; 
S.Top2 = the MaxSize; 

void the Push (struct * PTRS DStack, the ElementType Item, the Tag int) 
{ 
	IF (PtrS-> PtrS- of Top1 +. 1 ==> Top2) 
	{ 
		the printf ( "stack full"); 
		return; 
	} 
	IF (the Tag ==. 1) 
		PtrS-> the Data [ ++ (PtrS-> of Top1)] = Item; 
	the else 
		PtrS-> the Data [- (PtrS-> Top2)] = Item; 
	return; 
} 

the ElementType Pop (struct DStack * PTRS, the Tag int) 
{ 
	// the Tag as a distinguished two stacks flag, the value 1 and 2 
	IF (the Tag == 1)  
	{
		IF (PtrS-> of Top1 == -1)
		{
			printf("堆栈1空");
			return NULL; 
		}
		else
		{
			return PtrS->Data[(PtrS->Top1)--];
		}
	}
	else
	{
		if(PtrS->Top2 == MaxSize)
		{
			printf("堆栈2空");
			return NULL; 
		}
		else
		{
			return PtrS->Data[(PtrS->Top2)++];
		}
	}
}

  

3. Chain stack

// stack of linked storage 
typedef struct SNODE * Stack; 
struct SNODE 
{ 
	the ElementType the Data; 
	struct the Next SNODE *; 
}; 
// stack pointer should be in the top of the head of the linked list 

// 1. Initialize the stack (Stack create empty) 
Stack CreateStack () 
{ 
	stack S; 
	S = (stack) the malloc (the sizeof (struct SNODE)); 
	-S-> the Next = NULL; 
	return S; 
} 

// determines whether the stack is empty 
int the IsEmpty (stack S) 
{ 
	return (-S- > the Next == NULL); 
} 

// node insertion 
void the Push (the ElementType Item, Stack S) 
{ 
	struct SNODE * TmpCell; 
	TmpCell = (struct SNODE *) the malloc (the sizeof (struct SNODE)); 
	TmpCell-> the Data Item = ;  
	TmpCell-> = the Next -S-> the Next;
	-S-> = the Next TmpCell; 
}

// 删除结点
ElementType Pop(Stack S)
{
	struct SNode *FirstCell;
	ElementType TopElem;
	if(IsEmpty(S))
	{
		printf("堆栈空");
		return NULL; 
	}
	else
	{
		FirstCell = S->Next;
		S->Next = FirstCell->Next;
		TopElem = FirstCell->Data;
		free(FirstCell);
		return TopElem;
	}
} 

  

Guess you like

Origin www.cnblogs.com/mjn1/p/11441604.html