【发布时间】:2016-06-06 12:24:32
【问题描述】:
我尝试在 c++ 上实现链表。下面是我的代码:
#include<iostream>
using namespace std;
class lnk
{
struct node
{
int data;
node *next;
};
node* insert(node *head,int data)
{
if(head==NULL)
{
node *temp;
temp->data=data;
temp->next=NULL;
head=temp;
}
else
head->next=insert(head->next,data);
return head;
}
node* find(node *head,int data)
{ while(head!=NULL)
{
if(head->data==data)
return head;
else
head=head->next;
}
cout<<"sorry";
return NULL;
}
void delete(node *head,int data)
{
node *temp=find(head,data);
if(temp==NULL)
;
else
if(head==temp)
{
head=head->next;
}
else
{
node *temp1=head;
while(temp1->next!=temp)
{
temp1=temp1->next;
}
temp1->next=temp->next;
delete temp;
}
}
void display(node *head)
{
while(head!=NULL)
{
cout<<head->data;
head=head->next;
}
}
};
int main()
{
lnk o1;
node *head=NULL;
head=o1.insert(head,5);
head=o1.insert(head,8);
o1.delete(&head,5);
o1.display(head);
return 0;
}
问题是我无法正确编译代码。首先,在 main() 中创建指针头时,它指出节点未在范围内声明。我尝试将定义切换为 public,但没有成功。 我也收到函数签名不匹配的错误。可能是由于没有正确声明头指针。 请评估并向我提供该问题的有效编译代码。
【问题讨论】:
-
发布编译错误,指出错误中提到的行号。
-
请使用正确的变量、类和函数名
-
您确实需要修复缩进。因为它使您的代码几乎不可读。
-
您错过了面向对象编程以及内存分配的必要性。我建议您回顾一下您的所有阅读材料并重新开始。
-
用新问题替换旧问题会使现有答案变得难以理解且毫无意义。我已经回滚到原来的了。如果您有后续问题,请发布新问题,而不是编辑已回答的问题。
标签: c++ linked-list