c - 在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
. 使用. %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);
如果不想添加start
andend
值,或者想多次处理子序列,可以在结构中添加一个参数int index
来跟踪每个节点的顺序。
typedef struct node
{
char city[20];
int weight;
int index
struct node *next;
}node;
推荐阅读
- python - 用逗号替换空格,除了行尾python
- tensorflow - 用于回归张量流的 3D 张量,目标值也是 3D 张量
- android - 在 Android 11 setMediaSession on Notification 然后调用 stopSelf 不会触发 MediaBrowserServiceCompat 中的 onDestroy
- mysql - 如何使用 PDO 获取行数?
- python - Python - 如何将此模式(数字/数字)与正则表达式匹配?
- c - 使用 OpenSSL API 创建服务器时出现“tlsv1 alert unknown ca”
- java - 使用spring boot在数据库问题中存储两次的数据
- apollo - 如果突变更改了嵌套子字段,Apollo 会自动更新缓存吗?
- pyspark - Pyspark 动态转换列
- python-3.x - 读入 rdd 以获取特定的行值