簡體   English   中英

在 c 中將加權邊添加到我的鏈表圖中

[英]Adding weighted edges to my linked list graph in 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 。 我會很感激任何幫助。 謝謝!

你只需要使用scanf作為你用於city int使用類型格式%d

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);

那是你想要的嗎?

更新:

如果要請求鏈表的子序列,可以在創建和顯示 function 中添加兩個參數startend

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

對於創建 function:

    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));
        }
        ...
    }

為了顯示 function,您可以使用counter來獲取列表中節點的順序:

   int counter = 0;

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

然后,當您調用 function 時,例如,您想從第 2 個節點打印到第 4 個節點。

displayList(HEAD, 1, 3);

如果您不想添加startend值,或者您想多次處理子序列,您可以在結構中添加一個參數int index用於跟蹤每個節點的順序。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM