Monday, December 5, 2016

C++ Link List Questions and Answers

1. Following Link List shown in Diagram A needs to be converted to the Link List given in   Diagram B. Show all the steps needed to do the conversion using the given Link object pointers.


Answer-01  
    
    P3 = P3→Next
    P3→Next = First→Next
    First→Next = P3
    P2 = P2→Next
    P2→Next = NULL


2. The following ordered Link List is given to you, write a method called orderedInsert to insert a Link at the correct position.(Hint: Ordered list is a Link List where the elements are sorted in either Ascending or Descending order)


Answer

void LinkedList::orderedInsert(int value)
    {
        Link *previous = first, *current = first;
        while (current!=NULL)
        {
            if (value < current→dData)
            {
               break;   
            }
            else
            {
                previous = current;
                current = current→next; 
            }
        }
           Link *newLink = new Link(value);
        NewLink→next = current;
        if (current == first)
           first = newLink; 
        else 
           previous→next = newLink;
    }

3. Implement a destructor for the LinkedList class.

LinkList::~LinkList()
   {
      cout << "Destructor called";
      Link *current = first;       // start at beginning of list
      Link *previous = current;
      while(current != NULL)      // until end of list,
      {
         previous = current;
         current = current->next;  // move to next link
         delete previous;

      }
   }

4. Show step by step how binary search would search for the following items from the data array given below.

(a) Search for 67
(b) Search for -90
(c) Search for 89

Data Array

0 1 2 3 4 5 6 7 8 9
        10   20    40     67 78 79 85 90 95 125
↑                                                                        ↑
bottom                                                          top





No comments:
Write comments
Recommended Posts × +