如何在C中的邻接列表中插入节点?

时间:2016-04-24 05:59:37

标签: c nodes adjacency-list

我想创建一个adjacency list,其中包含三个struct,如下所示。现在我正在研究插入方法,它只是在每一行中插入第一个节点。但是,当我尝试用第一个节点打印所有行时,它什么都不打印。在int main()中,当我按照id和name输入“InsertNode”时,它将调用方法并插入节点。我确信我的printmain方法是正确的。我的插入方法的哪一部分出错了?非常感谢!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node{
    char name[100];
    int id;
    struct Node *next;
} Node;
typedef struct Row{
    Node *header;
    struct Row *next;
} Row;
typedef struct{
    Row *header;
} Adj_List;


void InsertNode(Adj_List *g, int x, char n[]){
    Row *p = g->header;
    Node *p_Node;
    if(p=NULL){
        p_Node=new Node;
        p_Node=p->header;
        p_Node->id=x;
        strcpy(p_Node->name,n);
        p_Node->next=NULL;
        p->next=NULL;
    }else{
        while (p!=NULL){
            p_Node=p->header;
            if(strcmp(p_Node->name,n)==0){
                printf("NodeExist\n");
            }else if(p=NULL){
                p_Node=new Node;
                p_Node=p->header;
                p_Node->id=x;
                strcpy(p_Node->name,n);
                p_Node->next=NULL;
                p->next=NULL;
            }else{
                p=p->next;
            }
        }
    }
}

void PrintAdjacencyList(Adj_List *g){
    Row *p=g->header;
    while (p!=NULL){
        Node *p_Node=p->header;
        printf("%s",p_Node->name);
        p_Node=p_Node->next;
        int flag=0;
        while(p_Node!=NULL){
            if (!flag){
                printf(": %s",p_Node->name);
                flag=1;
            }
            else
                printf(" - %s",p_Node->name);
                p_Node=p_Node->next;
            }
        printf("\n");
        p=p->next;
    }
}

int main(){
    char command[100];
    Adj_List g;
    g.header=NULL;

    while (scanf("%s",command)){
        if (strcmp(command, "insert")==0){
            int x;
            char name[100];
            scanf("%d %s\n",&x, name);
            InsertNode( &g, x, name);
        }
        else if (strcmp(command, "Print")==0){
            PrintAdjacencyList( &g);
        }
    }
}

0 个答案:

没有答案