Consider the following implementation of singly-linked lists//Java class ListNod
ID: 3583152 • Letter: C
Question
Consider the following implementation of singly-linked lists//Java class ListNodo {public ListNode(E data. ListNode next}{this.data - data; this.next - next; public E data; public ListMode next;//c ++ template class ListNode {public: E data; ListNode *next; ListNode(E& iten, ListNode * ptr = NULL): data(item), next(ptr) {>); A list consists of nodes, where each node stores a value and a pointer to the next node. A list can he represented as the pointer to the first node in the list. Write the following functions in C++ or Java. You will receive extra points if your functions use recursion correctly. last (1st): This function returns the last node value of list 1st. You can assume that 1st is not empty. take (1st, n); This function returns the n-element prefix of 1st if n is less than the size of 1st; otherwise, it returns 1st itself. find_last_of (1st.elm); This function returns the number of the last occurrence of value elm in list 1st, counting from 0. It returns -1 if elm does not occur in 1st. For equality testing, use == for C++ and equals for Java.Explanation / Answer
Probably, this could achieve, the requirement for the first 2 methods:
#include <iostream>
using namespace std;
template <typename E>
class ListNode
{
public:
E data;
ListNode<E> *next;
ListNode(E& item, ListNode<E> *ptr = NULL): data(item), next(ptr) {}
};
//last(lst): This function returns the last node value of list lst.
//You can assume that lst is not empty.
template <typename E>
E last(ListNode<E> *head)
{
if(head->next == NULL)
return head->data;
else
return last(head->next);
}
//take(lst, n): This function returns the n-element prefix of lst if n is less than the
//size of lst; otherwise, it returns lst itself.
template <typename E>
ListNode<E> take(ListNode<E> *head, int n)
{
ListNode<E> *newList, *first;
for(int i = 0; i < n; i++)
{
ListNode<E> *temp = new ListNode<E>(head->data, head->next);
if(i == 0)
{
newList = temp;
first = newList;
}
else
newList->next = temp;
head = head->next;
if(head == NULL)
return first;
}
return first;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.