In: Computer Science
write code to manage a linked list using recursive approach. (Using this code) C++ IN Unix.
// app.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
void find(LinkedList& list, char ch)
{
if (list.find(ch))
cout << "found ";
else
cout << "did not find
";
cout << ch << endl;
}
int main()
{
LinkedList list;
list.add('x');
list.add('y');
list.add('z');
cout << list;
find(list, 'y');
list.del('y');
cout << list;
find(list, 'y');
list.del('x');
cout << list;
find(list, 'y');
list.del('z');
cout << list;
find(list, 'y');
return 0;
}
//-------------------
//linkedlist.h
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <ostream>
class LinkedList
{
public:
LinkedList();
~LinkedList();
void add(char ch);
bool find(char ch);
bool del(char ch);
friend std::ostream&
operator<<(std::ostream& out, LinkedList&
list);
};
#endif // _LINKED_LIST_
//-------------------------
//makefile
CC = g++
CPPFLAGS = -Wall -g -std=c++11
app: app.o linkedlist.o
app.o: linkedlist.h
linkedlist.o: linkedlist.h
.PHONY: clean
clean: # clean
the directory
$(info --
cleaning the directory --)
rm -f *.o
rm -f app
//-----------------------
// Recursive CPP program to recursively insert
// a node and recursively print the list.
#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
Node*
next;
};
// Allocates a new node with given data
Node *newNode(
int
data)
{
Node *new_node
=
new
Node;
new_node->data =
data;
new_node->next =
NULL;
return
new_node;
}
// Function to insert a new node at the
// end of linked list using recursion.
Node* insertEnd(Node* head,
int
data)
{
// If linked list is
empty, create a
// new node (Assuming
newNode() allocates
// a new node with
given data)
if
(head
== NULL)
return
newNode(data);
// If we have not
reached end, keep traversing
//
recursively.
else
head->next
= insertEnd(head->next, data);
return
head;
}
void
traverse(Node* head)
{
if
(head
== NULL)
return
;
// If head is not
NULL, print current node
// and recur for
remaining list
cout <<
head->data <<
" "
;
traverse(head->next);
}
// Driver code
int
main()
{
Node* head =
NULL;
head =
insertEnd(head, 6);
head =
insertEnd(head, 8);
head =
insertEnd(head, 10);
head =
insertEnd(head, 12);
head =
insertEnd(head, 14);
traverse(head);
}