【发布时间】:2017-12-01 03:46:10
【问题描述】:
我正在尝试在下面的代码中将点积计算公式实现到链表实现中,但出现以下错误: 请求'B'中的成员'add_node',它是指针类型'linked_list {aka node*}'(也许你打算使用'->'?) 我怎样才能清除它并制作工作代码?我也不想使用类
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
int index;
node *next;
};
typedef node* linked_list;
node *head = NULL;
node *tail = NULL;
void add_node(int i,int n)
{
node *tmp = new node;
tmp->index = i;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void display(node *head)
{
while(head!=0)
{
cout << head->index <<" ," << head->data << endl;
display(head->next);
break;
}
}
int main()
{
linked_list A;
A.add_node(2,7);
A.add_node(4,5);
A.add_node(7,8);
A.add_node(9,4);
linked_list B;
B.add_node(3,5);
B.add_node(4,6);
B.add_node(9,5);
int product=0;
while(A!=0 && B!=0)
{
if(A->index == B->index)
{
product = product + A->data * B->data;
A=A->next;
B=B->next;
}
else if(A->index < B->index)
{
A=A->next;
}
else
{
B=B->next;
}
}
return product;
return 0;
}
【问题讨论】:
-
您的
node结构没有成员函数。通常使用带有指针的 typedef 会导致悲伤。 -
不得不说,这些老师肯定会想出新奇的方法来掩饰每天来这里20次的“链表作业”问题。使用链表计算点积?下一步是什么?
-
您似乎试图在单个全局
head和tail上运行两个不同的链表。这行不通。我认为您想创建一个链表类来将两者分开。 -
当我使用类时,我在主函数 truct node { int data; 中的 While 循环出现问题整数索引;节点*下一个; };类linked_list {私有:节点*head,*tail;公共:linked_list(){头=空;尾=空; } void add_node(int i,int n){} void display(node *head){}
-
您应该问一个新问题,而不是对这个问题进行彻底的改变并使(当时正确)答案无效。我要恢复你上次的编辑。但是链表是正确的方法,而且你很接近。您要做的是遍历链表中的节点,而不是链表。您可以从列表中获取头节点并在
while循环中执行您正在执行的操作。
标签: c++ vector linked-list