当前位置: 首页 > >

数据结构栈 学*笔记

发布时间:

栈是先进后出的数据结构。


下面直接上代码了。下面使用数据模仿栈式结构。



//
// main.cpp
// StudyC++
//
// Created by 杜甲 on 14-9-12.
// Copyright (c) 2014年 杜甲. All rights reserved.
//

#include //std::cout
#include
using namespace std;

#define MaxSize 10
int stack[MaxSize];
int top = -1;

void push(int value)
{
int i;
if (top >= MaxSize)
std::cout<<"
The stack is full"< else
{
std::cout<<"
The stack content before(top->bottom):"< for (i = top; i >= 0; i--)
cout<
top++;
stack[top] = value; //将数据放入数组中
cout<<"The stack content after push(top->bottom):"< for (i = top; i >= 0; i--)
cout<
}

}

int pop()
{
int temp;
int i;
if (top < 0)
{
cout<<"The stack is empty!"< return -1;
}

cout<<"The stack content before(top->bottom):"<
for (i = top; i >= 0; i--)
cout<
temp = stack[top];
top--;
printf("
The pop value is [%d]",temp);
printf("
The stack content after pop(top->bottom):");
for (i = top; i >= 0; i--)
printf("[%d]",stack[i]);
printf("
");


return temp;
}





int main(int argc, const char * argv[])
{

//测试
push(3);
push(5);
push(9);
int num = pop();
printf("num = %d
",num);
num = pop();
printf("num = %d
",num);
push(7);

return 0;
}






用链表模仿栈



//
// main.cpp
// StudyC++
//
// Created by 杜甲 on 14-9-12.
// Copyright (c) 2014年 杜甲. All rights reserved.
//

#include //std::cout
#include
using namespace std;

struct s_node
{
int data;
struct s_node *next;
};
typedef struct s_node s_list;
typedef s_list *link;
link stack = nullptr;

void print_stack()
{
link temp = nullptr;
temp = stack;
if (temp == nullptr)
printf("The stack is empty!
");
else
{
while (temp != nullptr)
{
printf("[%d]",temp->data);
temp = temp->next;
}
printf("
");
}


}

void push(int value)
{
link newnode;
printf("
The stack content before(top->bottom):");
print_stack();

//初始化
newnode = (link)malloc(sizeof(s_list));
//赋值
newnode->data = value;
//栈是先进后出 将之前的节点放到后面
newnode->next = stack;
//将新的放到前面
stack = newnode;


}

int pop()
{
link top;
int temp;
printf("
The stack content before(top->bottom):");
print_stack();
if (stack != nullptr)
{
top = stack;
stack = stack->next;
temp = top->data;
free(top);
return temp;

}else{
return -1;
}
}



int main(int argc, const char * argv[])
{
push(9);
push(10);

pop();

push(11);
print_stack();
return 0;
}
























原文地址:http://blog.csdn.net/qqmcy/article/details/39393941



友情链接: 时尚网 总结汇报 幼儿教育 小学教育 初中学习资料网