首页 > 解决方案 > 在c中将加权边添加到我的链表图

问题描述

所以我正在尝试构建一个图形数据结构,其中城镇作为节点,边作为它们之间的距离。我想为每个节点/位置创建一个邻接列表并添加一个加权边。到目前为止,我已经创建了一个链表程序,它询问用户他们想要多少个节点。然后,用户可以在创建每个节点时为其命名,并打印出带有节点的链表。

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

typedef struct node
{
    char city[20];
    int weight;
    struct node *next;
}node;

node *createLinkedList(int n);
void displayList(node *head);

int main()
{
    int n = 0;
    node *HEAD = NULL;
    printf("\nHow many nodes:\t");
    scanf("%d", &n);
    HEAD = createLinkedList(n);
    displayList(HEAD);

    return 0;
}

node *createLinkedList(int n)
{
    int i = 0;
    node *head = NULL;
    node *temp = NULL;
    node *p = NULL;

    for (i = 0; i < n; i++)
    {
        // create an individual node

        temp = (node*)malloc(sizeof(node));
        printf("\nEnter the name of the city: ", i+1);
        scanf("\t%s",(temp->city));
        temp->next = NULL;

        if (head == NULL) //if list is currently empty, then make temp as first node
        {
            head = temp;
        }
        else
        {
            p = head;
            while(p->next != NULL)
                p = p->next;
            p->next = temp;
        }
    }

    return head;
}

void displayList(node *head)
{
    node *p = head;

    while(p != NULL)
    {
        printf("\t%s->",p->city);
        p = p->next;
    }
}

现在,我希望用户指定每条边的权重并打印它。我自己尝试过这样做,但无济于事。我在顶部的结构中指定了一个 weight int 。我会很感激任何帮助。谢谢!

标签: cgraphlinked-list

解决方案


你只需要使用scanf你所使用的city. 使用. %d_int

printf("\nEnter the name of the city %d: ", i+1);
scanf("\t%19s",(temp->city));
printf("\nEnter the the weight of the city %d: ", i+1);
scanf("\t%d",&(temp->weight));

打印重量:

printf("weight = %d\n",p->weight);

那是你想要的吗?

更新:

如果要请求链表的子序列,可以在创建和显示函数中添加两个参数start, 。end

node *createLinkedList(int n, int start, int end);
void displayList(node *head, int start, int end);

对于创建功能:

    for (i = 0; i < n; i++) {
        ....
        if (start <= i && i <= end) {
            printf("\nEnter the the weight of the city %d: ", i+1);
            scanf("\t%d",&(temp->weight));
        }
        ...
    }

对于显示功能,您可以使用counter列表中节点的顺序:

   int counter = 0;

    while(p != NULL)
    {
        ...
        if (start <= counter && counter <= end) {
            printf("\n weight =  %d \n", p->weight);
        }
        ...
        counter++;
        p = p->next;
    }

然后,当您调用函数时,例如,您想从第 2 个节点打印到第 4 个节点。

displayList(HEAD, 1, 3);

如果不想添加startandend值,或者想多次处理子序列,可以在结构中添加一个参数int index来跟踪每个节点的顺序。

typedef struct node
{
    char city[20];
    int weight;
    int index
    struct node *next;
}node;

推荐阅读