Question

Problem Statement This problem provides you with a linked list composed of node objects chained together...

Problem Statement

This problem provides you with a linked list composed of node objects chained together via node pointers. Each node has a next pointer which points to the next node in the chain. The last node is identified by having a NULL (or nullptr) next pointer.

The linked lists for this problem store string data. Your task: identify the longest string stored in the linked list. If two strings are of the same length, return the string that occurred earlier in the linked list. If the linked list is empty, return the empty string.

Create a function longest, which takes in a pointer to the head of the linked list, and returns the longest string in the linked list.

The linked lists for this problem use the following class declaration:

class node {
public:
    string data;
    node* next;    
};

Notes and Constraints

  • The linked list starting at head contains between 0 and 10 nodes, inclusive.

Examples

  1. "apple->orange->banana->pear"->NULL
    
    return "orange"
    

Given Function

string longest(node* head) {
// fill in code here
}

Use the given function to solve the problem statement. Please follow the given notes and constraints. Please code this problem in C++.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PLEASE GIVE THUMB UP, THANKS

SAMPLE OUTPUT :

code:

#include<iostream>
#include<string.h>
using namespace std;

class node
{
   public:
       string data;
       node *next;
       node *head;
   node()
   {
       head=NULL;
   }
   void insert(string d)
   {
       node *P=new node();
       P->data=d;
       P->next=NULL;
       if(head==NULL)
       {
           head=P;
       }
       else
       {
           P->next=head;
           head=P;
       }
   }
};
string longest(node *List)
{
   node *ptr=List->head;
   string value="";
   while(ptr!=NULL)
   {
       if(ptr->data.length()>value.length())
       {
           value=ptr->data;
       }
       ptr=ptr->next;
   }
   return value;
}

int main()
{
   node *List=new node();
   List->insert("pear");
   List->insert("banana");
   List->insert("orange");
   List->insert("apple");
   cout<<longest(List)<<endl;
}

Add a comment
Know the answer?
Add Answer to:
Problem Statement This problem provides you with a linked list composed of node objects chained together...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT