孩子-兄弟法存储树并求结点数;
#include<stdio.h> #include<stdlib.h> #include<queue> using namespace std; int sum=0; int num=0; typedef struct node{ int data; struct node *firstchild,*nextbrother; }TNode,*LTNode; void creatTree(LTNode &T) { int v; printf ("输入节点信息(0表示空):\n"); scanf("%d",&v); if(v==0) T=NULL; else { T=(LTNode)malloc(sizeof(TNode)); T->data=v; printf("输入%d节点的firstchild:\n",T->data); creatTree(T->firstchild); printf("输入%d节点的nextbrother:\n",T->data); creatTree(T->nextbrother); } } int leaf1 (LTNode &T) {///层次遍历求叶子节点数 queue<LTNode>Q; LTNode p; if (T) { Q.push(T); while (!Q.empty()) { p=Q.front(); if (!p->firstchild) num++; if (p->firstchild) Q.push(p->firstchild); if (p->nextbrother) Q.push(p->nextbrother); } } return num; } int leaf(LTNode &T) { ///递归求叶子节点数 if(T) { if(!T->firstchild) sum++; leaf(T->firstchild); leaf(T->nextbrother); } return sum; } int main() { LTNode T; creatTree(T); leaf(T); leaf1 (T); printf ("此树叶子节点数为:%d\n",sum); printf ("此树叶子节点数为:%d\n",num); printf("\n"); return 0; }
已知图的邻接表,建立图的逆邻接表;
#include<stdio.h> #include<stdlib.h> #include<queue> //调用STL队列库函数 #include<stack> //调用STL栈库函数 #define max 20 using namespace std; int visited[max]={0}; typedef struct Arcnode{ int adj; struct Arcnode *nextarc; }Arcnode; typedef struct Vnode { int data; Arcnode *firstarc; }Vnode,Adjlist[max]; typedef struct{ Adjlist vertices; int vex,arc; }Algraph; int Locatevex(Algraph &G,int v) { int i,k=-1; for(i=0;i<G.vex;i++) if(v==G.vertices[i].data) { k=i; break; } return k; } void CreateAdjList(Algraph &G) { //创建图的邻接表 int i,j,k; int v1,v2; Arcnode *p,*s; printf ("输入图的顶点数与边数:\n"); scanf("%d%d",&G.vex,&G.arc); printf ("输入顶点信息:\n"); for( i=0;i<G.vex;++i) //初始化头结点 { scanf("%d",&G.vertices[i].data); G.vertices[i].firstarc = NULL; } printf ("输入一边依附的两个顶点:\n"); for( k=0;k<G.arc;++k) { //构造邻接表 scanf("%d%d",&v1,&v2); i=Locatevex(G,v1); j=Locatevex(G,v2); s=(Arcnode*)malloc(sizeof(Arcnode)); s->adj=j; s->nextarc=NULL; p=G.vertices[i].firstarc; if(!p) G.vertices[i].firstarc=s; else { while(p->nextarc) p=p->nextarc; p->nextarc=s; } } } void CreateAdjList1(Algraph &G1,Algraph &G) { //建立图的逆邻接表 Arcnode *p,*s; int i; for( i=0;i<G.vex;++i) //初始化头结点 { G1.vertices[i].data=G.vertices[i].data; G1.vertices[i].firstarc=NULL; } for (i=0;i<G.vex;i++) { p=G.vertices[i].firstarc; while(p) { s=(Arcnode*)malloc(sizeof(Arcnode)); s->adj=p->adj; s->nextarc=G1.vertices[i].firstarc; ///头插法建立每个顶点的链 G1.vertices[i].firstarc=s; p=p->nextarc; } } } int main () { Algraph a,b; CreateAdjList(a); CreateAdjList1(a,b); return 0; }