A. 利用两个栈模拟实现一个队的入队和出队运算 用c++实现
首先队列queue的基本操作是:1. 插入 2. 删除
用两个堆栈stack1 , stack2来实现上述两种操作无非就是:
队列插入元素x,就往stack1的栈顶插入元素x。当要弹出队列的时候,再把这个栈顶元素从stack1中pop掉,并插入到stack2中。
这样一来,先插入的元素,对于stack2就在栈顶的位置了。如此一来,两个堆栈就成功地实现了队列了。
代码如下:
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class Queue
{
private:
stack<T> s1,s2;
public:
Queue()
{
}
//“队列”插入元素
void push(T element)
{
s1.push(element);
}
void pop()
{
// s2不空,则s2的栈顶元素为虚拟队列最前面的元素
if(!s2.empty())
s2.pop();
// s2为空,说明s1的栈底元素为虚拟队列最前面的元素
// 应现将s1中的所有元素pop到s2中,再输出栈顶元素
else
{
while(!s1.empty())
{
T tmp = s1.top();
s1.pop();
s2.push(tmp);
}
s2.pop();
}
}
// front() 输出队列顶的元素,执行过程与pop() 函数相似,不再赘述.
T front()
{
if(!s2.empty())
return s2.top();
else
{
while(!s1.empty())
{
T tmp = s1.top();
s1.pop();
s2.push(tmp);
}
return s2.top();
}
}
};
int main() {
Queue<int> q;
q.push(1);
q.push(2);
q.push(4);
q.push(5);
q.pop();
cout << q.front() << endl;
return 0;
}
B. C/C++线程安全型队列的实现
首先,互斥量这种线程相关的内容是平台相关的,我假设你用的是windows平台开发。
其次,说明一下我的开发环境,vs2008,控制台程序,空的工程。
最后给你贴代码,分文件来看。
===头文件QueueNode.h===
===你需要的节点数据可能不是整数,只要将typedef int QUEUEDATA这一句的int换成你想要的类型即可,但要注意,这个类型必须实现赋值操作符重载,相等比较操作符重载,以及复制构造函数===
#ifndef _QUEUE_NODE_H_
#define _QUEUE_NODE_H_
typedef int QUEUEDATA;
typedef struct node
{
QUEUEDATA data;
node* m_pNext;
}QUEUENODE;
#endif
===队列头文件Queue.h,有平台相关内容,请注意===
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include "QueueNode.h"
#include <Windows.h>
class ThreadSafeQueue
{
public:
ThreadSafeQueue();
virtual ~ThreadSafeQueue();
bool InitQueue();
void EnQueue(const QUEUEDATA& data);
void DeQueue();
void Clear();
const QUEUENODE* Find(const QUEUEDATA& data) const;
void Print();
protected:
HANDLE m_hMutex;
QUEUENODE* m_pQueueHead;
};
#endif
===队列函数实现文件Queue.cpp===
#include "Queue.h"
#include <iostream>
ThreadSafeQueue::ThreadSafeQueue()
{
m_pQueueHead = new QUEUENODE;
m_pQueueHead->m_pNext = 0;
}
ThreadSafeQueue::~ThreadSafeQueue()
{
Clear();
delete m_pQueueHead;
CloseHandle(m_hMutex);
}
bool ThreadSafeQueue::InitQueue()
{
m_hMutex = CreateMutex(0, FALSE, 0);
return (m_hMutex!=0);
}
void ThreadSafeQueue::EnQueue(const QUEUEDATA& data)
{
WaitForSingleObject(m_hMutex, INFINITE);
QUEUENODE* pNode = new QUEUENODE;
pNode->data = data;
pNode->m_pNext = 0;
QUEUENODE* pTemp = m_pQueueHead;
while (pTemp->m_pNext != 0)
{
pTemp = pTemp->m_pNext;
}
pTemp->m_pNext = pNode;
ReleaseMutex(m_hMutex);
}
void ThreadSafeQueue::DeQueue()
{
WaitForSingleObject(m_hMutex, INFINITE);
QUEUENODE* pNode = m_pQueueHead->m_pNext;
if (pNode != 0)
{
m_pQueueHead->m_pNext = pNode->m_pNext;
delete pNode;
pNode = 0;
}
ReleaseMutex(m_hMutex);
}
const QUEUENODE* ThreadSafeQueue::Find(const QUEUEDATA& data) const
{
WaitForSingleObject(m_hMutex, INFINITE);
QUEUENODE* pNode = m_pQueueHead->m_pNext;
while (pNode != 0)
{
if (pNode->data == data)
{
break;
}
pNode = pNode->m_pNext;
}
return pNode;
ReleaseMutex(m_hMutex);
}
void ThreadSafeQueue::Clear()
{
WaitForSingleObject(m_hMutex, INFINITE);
QUEUENODE* pNode = m_pQueueHead->m_pNext;
QUEUENODE* pTemp = 0;
while (pNode != 0)
{
pTemp = pNode->m_pNext;
delete pNode;
pNode = pTemp;
}
m_pQueueHead->m_pNext = 0;
ReleaseMutex(m_hMutex);
}
void ThreadSafeQueue::Print()
{
WaitForSingleObject(m_hMutex, INFINITE);
QUEUENODE* pNode = m_pQueueHead->m_pNext;
while (pNode != 0)
{
std::cout << pNode->data << "\t";
pNode = pNode->m_pNext;
}
std::cout << std::endl;
ReleaseMutex(m_hMutex);
}
===测试代码文件main.cpp,包含了测试用可执行程序,两个操作queue的线程,需要说明的是,我本来打算用WaitMultipleObjects函数来等待两个线程都结束,但是没搞清楚是什么问题没有卡住,不打算继续纠缠它了,所以让主线程Sleep了5秒钟===
#include "Queue.h"
#include <iostream>
DWORD WINAPI HandleQueue(void* pParam);
DWORD WINAPI HandleQueue2(void* pParam);
int main()
{
ThreadSafeQueue queue;
queue.InitQueue();
HANDLE hThread[2] = {0};
DWORD threadID = 0;
hThread[0] = CreateThread(NULL, 0, HandleQueue, (void*)(&queue), NULL, &threadID);
hThread[0] = CreateThread(NULL, 0, HandleQueue2, (void*)(&queue), NULL, &threadID);
//WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
Sleep(5000);
queue.Print();
queue.Clear();
return 0;
}
DWORD WINAPI HandleQueue(void* pParam)
{
ThreadSafeQueue* pQueue = reinterpret_cast<ThreadSafeQueue*>(pParam);
for (int i = 0; i < 100; i++)
{
std::cout << "HandleQueue EnQueue" << std::endl;
pQueue->EnQueue(i);
}
for (int i = 0; i < 50; i++)
{
std::cout << "HandleQueue DeQueue" << std::endl;
pQueue->DeQueue();
}
return 0;
}
DWORD WINAPI HandleQueue2(void* pParam)
{
ThreadSafeQueue* pQueue = reinterpret_cast<ThreadSafeQueue*>(pParam);
for (int i = 0; i < 100; i++)
{
std::cout << "HandleQueue2 EnQueue" << std::endl;
pQueue->EnQueue(i+100);
}
for (int i = 0; i < 50; i++)
{
std::cout << "HandleQueue2 DeQueue" << std::endl;
pQueue->DeQueue();
}
return 0;
}
新建一个空的控制台程序工程,向工程中加入这几个文件,编译之后可以直接运行。
第一个线程投入队列100个元素,出队50个元素,第二个线程同样。最后主线程输出队列中最后的内容,然后清空。
队列用链表实现,可以试想一下,如果线程同步没有处理,指针操作时一定会引起崩溃
C. c++如何定义一个结构体队列
使用标准模板库(STL)中的std::queue就可以,不一定要用指针。比如:
#include<queue>
structMyStruct
{
intnum;
};
intmain()
{
//定义队列
std::queue<MyStruct>q;
MyStructs1;
s1.num=1;
//插入队列
q.push(s1);
//取出队首元素
MyStructs1_=q.front();
//队首元素从队列中移除
q.pop();
return0;
}
队列的特征是先进先出(FIFO),所以push元素会放到队尾,pop元素会取出队头。
除此之外STL还提供了双端队列(deque)。顾名思义,双端队列可以在队列两头进行操作。所以提供了对应的*front和*back的操作。
以下是参考代码:
#include<queue>
#include<iostream>
structMyStruct
{
intnum;
};
intmain()
{
//定义双端队列
std::deque<MyStruct>q;
MyStructs1;
s1.num=1;
//插入队尾
q.push_back(s1);
MyStructs2;
s2.num=5;
//插入队首
q.push_front(s2);
//取出队首元素
MyStructs2_=q.front();
MyStructs1_=q.back();
std::cout<<"s2="<<s2_.num<<std::endl;
std::cout<<"s1="<<s1_.num<<std::endl;
//队首元素从队列中移除
q.pop_front();
//队尾元素从队列中移除
q.pop_back();
//判断队列是否为空
if(q.empty())
{
std::cout<<"Enpty"<<std::endl;
}
return0;
}
std::queue参考:
http://www.cplusplus.com/reference/queue/queue/
std::deque参考:
http://www.cplusplus.com/reference/deque/deque/
D. C++中"std::"是什么意思
在C++中,std其实就是standard标准的意思。
例如std::cin就是标准输入,std::cout就是标准输出的意思。
C++是C语言的继承,它既可以进行C语言的过程化程序设计,又可以进行以抽象数据类型为特点的基于对象的程序设计,还可以进行以继承和多态为特点的面向对象的程序设计。C++擅长面向对象程序设计的同时,还可以进行基于过程的程序设计,因而C++就适应的问题规模而论,大小由之。
C++不仅拥有计算机高效运行的实用性特征,同时还致力于提高大规模程序的编程质量与程序设计语言的问题描述能力。
E. 本人使用Dev C++5.6.3,请问-std=c++11在源代码哪里插入
【工具】->【编译器选项】->【代码生成/优化】->【代码生成】->然后在"语言标准"下拉列表选择ISO C++ 11 或者 GNU C++ 11标准即可。
或者
【工具】->【编译器选项】->【编译器】 在“ 编译时加入一下命令"文本框中加入 -std=c++11
F. 帮忙些一个C语言队列的程序, 要求只有一个文件"queue.c".
我在写,但是你的图片显然看不到。。。。
写好了,测试无误,代码如下。我不能看到你的图片,因而,无法知道你的person结构体里面到底有些什么,我示意地给出了名字、年龄、优先级,你可以自主往里面添加,就增加几个单词而已啦。MAX_HEAP_SIZE我不太明白用作何种意义,就当作最大不能超过MAX_HEAP_SIZE个人来处理了,不合适你可以很容易修改。(联系方式[email protected])
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHARACTERS 30
#define MAX_HEAP_SIZE 100
#define MAX_PRIORITY 100
#define MIN_PRIORITY 0
/* define struct of a person */
struct person{
char *name;
int age;
int priority;
struct person *Next;
};
typedef struct person Person;
typedef struct person * Element;
/* implement the queue data structure */
/* using an additional head to simplify logic */
Element Head = (Element)malloc(sizeof(Person));
Element Rear = Head;
int PersonCount = 0;
/* function declarations */
Element GetInput(); /* Obtain the user's input */
int Enqueue(Element);/* Enqueue a person */
void Dequeue();/* Dequeue the person at the top of heap */
void printPerson(Element);/* Print a person's information */
void freeElem(Element);/* Free an element */
void Dump();/* Dump all persons' information in the heap */
void Exit();/* Free heap and exit */
int main()
{
while(true)
{
printf("\nPlease select a menu option:\n"\
"1) Enqueue a person\n"\
"2) Dequeue the next person\n"\
"3) Dump the contents of the heap\n"\
"4) Quit the program\n"\
"Enter an option: ");
int choice;
scanf("%d", &choice);
switch(choice)
{
case 1:
Element elem;
if((elem = GetInput())!= NULL)
if(Enqueue(elem) == 0)
printf("Succeed!\n");
break;
case 2:
Dequeue();
break;
case 3:
Dump();
break;
case 4:
Exit();
break;
default:
fprintf(stderr, "Invalid choice!\n");
break;
}
}
}
Element GetInput()
{
/* if heap is full, not allow to enqueue */
if (PersonCount > MAX_HEAP_SIZE)
{
fprintf(stderr, "Heap is full!\n");
return NULL;
}
/* input like: Michael 20 90 */
printf("Input person's information in order of Name, Age and Priority :\n");
Element elem = (Element)malloc(sizeof(Person));
elem->name = (char*)malloc(MAX_CHARACTERS);
fflush(stdin);
scanf("%s%d%d", elem->name, &elem->age, &elem->priority);
/* check the validation of input */
if (elem->age <= 0 || elem->age > 130 || elem->priority > MAX_PRIORITY || elem->priority < MIN_PRIORITY)
{
fprintf(stderr, "Invalid personal information! Abort!\n");
freeElem(elem);
return NULL;
}
elem->Next = NULL;
return elem;
}
int Enqueue(Element elem)
{
/* if heap is null, deal with it */
if(Head == Rear)
{
Head->Next = Rear = elem;
return 0;
}
/* if heap contains more than one element */
Element tmp;
for (tmp = Head; tmp != Rear; tmp = tmp->Next)
{
/* implement the priority queue */
if(elem->priority >= tmp->Next->priority)
{
elem->Next = tmp->Next;
tmp->Next = elem;
return 0;
}
}
/* if the element being enqueued has the lowest priority */
if(tmp == Rear)
{
tmp->Next = Rear = elem;
return 0;
}
return 1;
}
void Dequeue()
{
/* if the queue is empty */
if (Head == Rear)
{
fprintf(stderr, "The queue is empty!\n");
return;
}
Element tmp = Head->Next;
/* print person's information */
printPerson(tmp);
Head->Next = tmp->Next;
/* free element */
freeElem(tmp);
}
void printPerson(Element elem)
{
if(NULL == elem)
{
fprintf(stderr, "Element is NULL!\n");
exit(EXIT_FAILURE);
}
printf("Name: %s\t Age: %d\t Priority: %d\n", elem->name, elem->age, elem->priority);
}
void freeElem(Element elem)
{
free(elem->name);
free(elem);
}
void Dump()
{
if (Head == Rear)
{
fprintf(stderr, "The queue is empty!\n");
return;
}
int index = 1;/* index starts from 1 */
Element tmp;
for (tmp = Head->Next; tmp != Rear; tmp = tmp->Next)
{
printf("Index: %d\tName: %s\t Age: %d\t Priority: %d\n", index, tmp->name, tmp->age, tmp->priority);
}
printf("Index: %d\tName: %s\t Age: %d\t Priority: %d\n", index++, tmp->name, tmp->age, tmp->priority);
}
void Exit()
{
/* if the queue if empty, free the head */
if (Head == Rear)
{
free(Head);
exit(0);
}
/* free all elements */
Element curr = Head->Next;
free(Head);
while (curr != Rear)
{
Head = curr->Next;
freeElem(curr);
curr = Head;
}
/* at last, free the rear element */
freeElem(Rear);
exit(0);
}
这个是数组优先级队列的实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* define debug */
#ifdef __DEBUG__
#include <stdarg.h>
void debug(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
#else
void debug(const char *fmt, ...)
{
}
#endif
/* common constraints */
#define MAX_CHARACTERS 30
#define MAX_HEAP_SIZE 100
#define MAX_PRIORITY 100
#define MIN_PRIORITY 0
/* define struct of a person */
typedef struct person{
char name[MAX_CHARACTERS+1];/* better to use char *name */
int priority;
} Person, *Element;
/* function declarations */
int isFull(int, int);/* decide whether the queue is full */
Element GetInput(); /* Obtain the user's input */
int Enqueue(Element *, Element, int *, int *);/* Enqueue a person */
void Dequeue(Element *, int *);/* Dequeue the person at the top of heap */
void Dump(const Element *, int, int);/* Dump all persons' information in the heap */
void Exit(Element *, int, int);/* Free heap and exit */
int main()
{
/* define the queue and allocate memory. Local to main function. */
/* can store MAX_HEAP_SIZE-1 elements */
Element *queue = (Element *)malloc(MAX_HEAP_SIZE * sizeof(Element *));
/* pointers to the queue, initially they point to zero */
int front, rear;
front = rear = 0;
/* for user's choice */
while(true)
{
printf("\nPlease select a menu option:\n"\
"1) Enqueue a person\n"\
"2) Dequeue the next person\n"\
"3) Dump the contents of the heap\n"\
"4) Quit the program\n"\
"Enter an option: ");
int choice;
fflush(stdin);
scanf("%d", &choice);
switch(choice)
{
case 1:
/* if heap is full, not allow to enqueue */
if (isFull(front, rear))
{
fprintf(stderr, "Heap is full!\n");
break;
}
/* if not, process the enqueue operation */
Element elem;
if((elem = GetInput())!= NULL)
if(Enqueue(queue, elem, &front, &rear) == 0)
printf("Insertion Successful.\n");
break;
case 2:
/* if the queue is empty */
if(rear == front)
{
printf("The heap is empty. No removal has occurred.");
break;
}
Dequeue(queue, &front);
break;
case 3:
Dump(queue, front, rear);
break;
case 4:
Exit(queue, front, rear);
break;
default:
fprintf(stderr, "Invalid choice!\n");
}
}
}
int isFull(int front, int rear)
{
/* circular queue is used here */
return (rear+1) % MAX_HEAP_SIZE == front;
}
Element GetInput()
{
/* allocate memory for a person on the heap */
Element elem = (Element)malloc(sizeof(Person));
/* input like:
* Enter the name: Bill Smith
* Enter the priority: 77
*/
printf("\nEnter the name: ");
fflush(stdin);
fgets(elem->name, MAX_CHARACTERS, stdin);
elem->name[strlen(elem->name)-1] = '\0';/* deal with the '\n' in the string*/
printf("Enter the priority: ");
fflush(stdin);
scanf("%d", &elem->priority);
/* check the validation of input */
if (elem->priority > MAX_PRIORITY || elem->priority < MIN_PRIORITY)
{
fprintf(stderr, "Insertion failed because of an invalid priority.\n");
free(elem);
return NULL;
}
return elem;
}
/* calling function is responsible for queue check */
int Enqueue(Element *queue, Element elem, int *front, int *rear)
{
/* if queue if empty */
if (front == rear)
{
*rear = (*rear + 1) % MAX_HEAP_SIZE;/* has a circular meaning */
return 0;
}
/* queue is not empty, compare before insertion*/
/* first write to the rear of the queue */
*rear = (*rear + 1) % MAX_HEAP_SIZE;
queue[*rear] = elem;
int pointer = *rear;
/* exchange to proper position of the queue */
Element tmp;
int next;
while(true)
{
if(pointer == 0)
next = MAX_HEAP_SIZE;
else
next = pointer - 1;
if(queue[pointer] > queue[next])
{
/* exchange */
tmp = queue[pointer];
queue[pointer] = queue[next];
queue[next] = tmp;
}
else
return 0;/* done with enqueue */
}
return 1; /* something happened unexpectedly */
}
/* the calling function is responsible for queue check */
void Dequeue(Element *queue, int *front)
{
*front = (*front + 1) % MAX_HEAP_SIZE;
printf("%s (Priority %d) has been removed.\n",\
(*queue[*front]).name, (*queue[*front]).priority);
}
void Dump(const Element *queue, int front, int rear)
{
/* if the queue is empty */
if(rear == front)
{
printf("The heap is empty.\n");
return;
}
printf("Index\tPriority\t\tName\n-----\t---------\t----------------------\n");
rear = (rear+1)%MAX_HEAP_SIZE;
int index = 0;/* index starts from 0 */
while((front = (front+1)%MAX_HEAP_SIZE) != rear)
{
printf("%d\t%d\t\t%s\n", index, (*queue[front]).priority, (*queue[front]).name);
++index;
}
}
void Exit(Element *queue, int front, int rear)
{
printf("\nProgram terminating...");
if(rear == front)
{
free(queue);
exit(0);
}
/* free the elements */
rear = (rear+1)%MAX_HEAP_SIZE;
while((front = (front+1)%MAX_HEAP_SIZE) != rear)
{
free(queue[front]);
}
/* free the array of pointers to elements */
free(queue);
exit(0);
}
G. std::queue怎么用啊,怎么遍历元素啊
int main(int argc, char *argv[])
{
queue<int> myQ;
for(int i=0; i<10; i++)
myQ.push(i);
for(int i=0; i<myQ.size(); i++)
{
cout << myQ.front()<<endl;
myQ.pop();
}
return 0;
}queue是STL的队列,有FIFO的特性。上面的程序是将0~9十个数字压入队列,然后依次出对queue的成员方法比较少,常用的也就那么几个,注意,要包含头文件<queue>对于priority_queue,他的原则是优先权大的先出队,也就是说,你在创建一个priority_queue的时候是可以指定每个元素的优先级的,优先级越大,出队越早,而queue只是传统意义上简单的队列。
H. 《STL源码分析》中如何priority_queue使用greater函数对象
首先查看手册,priority_queue的定义如下:
template<classT, classContainer=std::vector<T>, classCompare=std::less<typenameContainer::value_type>>classpriority_queue;
然后继续看模板的三个参数的说明
—————————以下直接摘抄的—————
Template parameters
T - The type of the stored elements.The behavior is undefined ifTis not the same type asContainer::value_type.(since C++17)
Container - The type of the underlying container to use to store the elements. The container must satisfy the requirements ofSequenceContainer, and its iterators must satisfy the requirements ofLegacyRandomAccessIterator. Additionally, it must provide the following functions with the usual semantics:
front()
push_back()
pop_back()
The standard containersstd::vectorandstd::dequesatisfy these requirements.
Compare - AComparetype providing a strict weak ordering.
—————————以上直接摘抄的—————
故可知,使用priority_queue需要给三个类来实现模板,其中第三个类就是那个比较函数,你问的,为什么要priority_queue<int, vector<int>, greater<int> > q1;已经回答完毕。
另外,可以参考std::less的定义,更深入学习第三个类的含义。已附在引用部分,自行查阅。
std::priority_queuestd::less
PS:第一个那家伙回答的什么东西!我本来是不想回答的。。。看见那家伙胡诌一气,气不过。
I. C++中"std::"是什么意思起什么作用
std是一个类(输入输出标准),它包括了cin成员和cout成员,using name space std ;以后才能使用它的成员。#include<iostream.h>中不存在类std,但是他又cin,out的相关函数,不需要使用命名空间了。而第二种标准#include<iostream>,它包含了一个类,在类的使用之前要预处理一下,using namespace std;就是这个功能,然后你就可以使用cin,cout这两个成员函数了,假设你不使用预处理(using namespace std;),麻烦加上std::cin或者std::cout再去使用它的成员函数(头文件中存在这个类)
J. 用队列实现按层次创建二叉树的源代码,最好是C语言
队列??你每输入一个节点将其存入队列中,再输入它的左孩子,它的左孩子也会入队,我们取的时候应先取该节点的左孩子,
LZ一定要用队列也行,但绝对不是正确的选择!
队列如下:
#include <iostream>
using namespace std;
typedef struct bitnode
{
char data;
struct bitnode *lchild,*rchild;
}*bitree,tree;
int number=0;
void createbitree(bitree &t)
{
char c;
int i=0,r=0,f=0;//r,f分别指向队首和队尾
bitree p=NULL,temp=NULL,pre=NULL,s[100];
s[0]=NULL;
int lflag[100]={0};
int rflag[100]={0};
printf("请输入根节点:");
t=new tree;
t->lchild=t->rchild=NULL;
scanf("%c",&t->data);
temp=pre=t->lchild;
s[++i]=t;
f=i;
p = t;
while(f!=r)
{
if(p->lchild==NULL&&lflag[i]==0)
{
printf("请输入%c的左孩子:",p->data);
fflush(stdin);
scanf("%c",&c);
if(c!='#')
{
p->lchild = new tree;
p = p->lchild;
p->lchild=p->rchild=NULL;
p->data = c;
s[++f]=p;
i = f;
lflag[i]=rflag[i]=0;
}
else
lflag[i]=1;
}
else if(p->rchild==NULL&&rflag[i]==0)
{
printf("请输入%c的右孩子:",p->data);
fflush(stdin);
scanf("%c",&c);
if(c!='#')
{
p->rchild = new tree;
p = p->rchild;
p->lchild=p->rchild=NULL;
p->data = c;
s[++f]=p;
i=f;
lflag[i]=rflag[i]=0;
}
else
{
rflag[i]=1;
p=s[++r];
i=r;
}
}
else
{
p=s[++r];
i=r;
}
}
}
void preorder(bitree &t)//遍历二叉树,输出函数
{
if (t!=0)
{
cout<<t->data<<",";
preorder(t->lchild);
preorder(t->rchild);
}
}
void main()
{
bitree t;
t=0;
createbitree(t);
cout<<"the value of the preorder value is:";
preorder(t);
}
在此,强烈建议LZ用栈,更符合树的输入层次:
#include <iostream>
using namespace std;
typedef struct bitnode
{
char data;
struct bitnode *lchild,*rchild;
}*bitree,tree;
int number=0;
void createbitree(bitree &t)
{
char c;
int i=0;
bitree p=NULL,temp=NULL,pre=NULL,s[100];
s[0]=NULL;
int lflag[100]={0};
int rflag[100]={0};
printf("请输入根节点:");
t=new tree;
t->lchild=t->rchild=NULL;
scanf("%c",&t->data);
temp=pre=t->lchild;
s[++i]=t;
p = t;
while(s[i]!=NULL)
{
if(p->lchild==NULL&&lflag[i]==0)
{
printf("请输入%c的左孩子:",p->data);
fflush(stdin);
scanf("%c",&c);
if(c!='#')
{
p->lchild = new tree;
p = p->lchild;
p->lchild=p->rchild=NULL;
p->data = c;
s[++i]=p;
lflag[i]=rflag[i]=0;
}
else
lflag[i]=1;
}
else if(p->rchild==NULL&&rflag[i]==0)
{
printf("请输入%c的右孩子:",p->data);
fflush(stdin);
scanf("%c",&c);
if(c!='#')
{
p->rchild = new tree;
p = p->rchild;
p->lchild=p->rchild=NULL;
p->data = c;
s[++i]=p;
lflag[i]=rflag[i]=0;
}
else
{
rflag[i]=1;
p=s[--i];
}
}
else
p=s[--i];
}
}
void preorder(bitree &t)//遍历二叉树,输出函数
{
if (t!=0)
{
cout<<t->data<<",";
preorder(t->lchild);
preorder(t->rchild);
}
}
void main()
{
bitree t;
t=0;
createbitree(t);
cout<<"the value of the preorder value is:";
preorder(t);
}
不懂追问!你的疑问往往是我要学习的地方!