Sarthak Mehra
Sarthak Mehra

Reputation: 359

Implementation of singly linked list

I tried implementing linked list on c++.Below here is my code:

#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;
 }

The problem is that I am unable to compile the code correctly.Firstly,while creating a pointer head in main(),it states that node is not declared in scope.I tried switching the definitions to public with no success. I am also getting error of function signature mismatch.Maybe it is due to the head pointer not properly declared. Please evaluate and provide me with a working compiled code for the problem.

Upvotes: 1

Views: 576

Answers (2)

Heto
Heto

Reputation: 595

First of all you need to declare them public:

class lnk
{
public:

After that you need to declare the scope of the node:

lnk::node *head=NULL;

Third don't use "delete". this is reserved keyword:

void deleteNode(node *head,int data)

Doing this three things will compile you're code. I don't think it will work. If you want an working example of linked list:

Segmentation fault (core dumped) when I delete pointer

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

lnk o1;
node *head=NULL;

node is an inner class in lnk. That's how you declared it. Either stick a

typedef lnk::node node;

at the beginning of main(), or replace all references in main() to node with lnk::node.

EDIT: forgot to notice that node is private. You'll also have to make it a public inner class.

Upvotes: 1

Related Questions