Recursive Print Function for Linked List - c++11

So my professor would like us to design recursive functions for a linked list from this class 'addressBookType' which is derived from 4 other classes. The program basically creates an address book with the person's name, address, date, and relationship, each of those has their own classes.
The recursive functions she wants to make are a print, append, delete, and sequential search.
But here's the problem. The main premise around a function being recursive is that it's supposed to call itself in the function definition right? I successfully made the recursive append function, but I'm having trouble with the recursive print function.
Here is what the original print function and the recursive print function are:
void addressBookType::displayList() const
{
ListNode *nodePtr; // To move through list
nodePtr = head; // start at the head of list
while(nodePtr != NULL) // while nodePtr points to a node, move through list
{
displayListRecursive(nodePtr);
nodePtr = nodePtr->next;
}
}
void addressBookType::displayListRecursive(ListNode *node) const
{
if(node != NULL)
{
(node->value).print();
displayListRecursive(node->next);
}
}
The trouble I'm having is that when I run the program, everything prints and then it starts printing at the second object until there is one object left. Here's what I mean when it prints:
1
2
3
4
2
3
4
3
4
4
I would paste what the actual output is but it is VERY lengthy, as each object displays the person's first name, last name, address, street, zipcode, city, state, date, and relationship type.
Whenever I take out the displayListRecursive(node->next) in the displayListRecursive function, everything prints fine. But then it's not really a recursive function right? Or is it? Anyone have some answers that can explain this? (I'm REALLY new to recursive)

I think the recursive definition is fine. It will print the node you provide and then call itself with the next one until its NULL.
So you just need to call the recursive function from the first node.
The problem is that you are calling it multiple times with all the nodes in the while loop of displayList.
I think that if you just remove the while loop it should work as you expect.
Something like this:
void addressBookType::displayList() const
{
displayListRecursive(head);
}
void addressBookType::displayListRecursive(ListNode *node) const
{
if(node != NULL)
{
(node->value).print();
displayListRecursive(node->next);
}
}

Related

The repetitive step in delete a specific node in a Linked List

//Deletes data given from the linked list
public void deleteByValue(T data) {
//if empty then simply return
if (isEmpty())
return;
//Start from head node
Node currentNode = this.headNode;
Node prevNode = null; //previous node starts from null
if(currentNode.data.equals(data)) {
//data is at head so delete from head
deleteAtHead();
return;
}
//traverse the list searching for the data to delete
while (currentNode != null) {
//node to delete is found
if (data.equals(currentNode.data)){
prevNode.nextNode = currentNode.nextNode;
return;
}
prevNode = currentNode;
currentNode = currentNode.nextNode;
}
}
}
Hi all, I am quite new to data structure and I am confused when I learned how to delete one specific value in the single linked list.
So when we traverse the LinkedList, we have a line like this
prevNode.nextNode = currentNode.nextNode;
I think this already means that we have connected "the previous node before the target node" and "the next node before the current node". Why do we still have these two lines after the traversing of the linked list?
prevNode = currentNode;
currentNode = currentNode.nextNode;
Are these two lines mean we are connecting the original previous node with the original next node? I always got lost when the code referred to the "currentNode".How can we tell which is the current "currentNode"?
Could someone help me with this? Visualized answer is appreciated. Thanks so much!
Why do we still have these two lines after the traversing of the linked list?
These are not after traversing; these are the traversing itself.
Some things to note:
An assignment to an attribute will mutate the list, like prevNode.nextNode = currentNode.nextNode does.
An assignment to a variable will not mutate the list, but can make a reference to a different node, like currentNode = currentNode.nextNode does. This really is the core of traversing: it makes the variable currentNode hop from one node to the next -- without changing anything to the list it is traversing.
In this specific algorithm, when the mutation with prevNode.nextNode = currentNode.nextNode is performed, the next thing that happens is a return -- so there is no further traversal happening.

Searching deep into Telerik Radtreview subtrees for a node with given value?

I have a RadTreeView C# component. The tree is nested, so some Nodes have their sub-trees, stored in Nodes property of upper-level Nodes.
Now I need to find a node by value. Node is hidden somewhere in subtrees. If I use call
RadTreeNode rtn= PagesTreeView.Nodes.FindNodeByValue(i.ToString());
where PagesTreeView is my tree, then it searches only across top-level nodes.
How I can Find Node by Value using not only Nodes from the current level of tree, but also dive into subtrees? Do I need to write such recursive search myself or there is a straightforward solution?
Recursively searching the RadComboBox
There isn't a built in function to recursively search, however you can roll your own pretty easiliy. This should work for you (not tested):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
FindNodeRecursive(node.Nodes, value);
}
return null;
}
}
And then call it like this:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
Yes, you would need to write your own recursive function to do the search. Another option if you are using the ASP.NET AJAX version of the control is the GetAllNodes() method. It returns all nodes in the tree hierarchy (I'm guessing it uses recursion under the hood). Once you have the entire list you would search it for the node you care about. The big drawback with that approach is if you have a lot of nodes the search could be slow and consume a lot of memory. Doing your own recursive search is the best approach.
See this article for more info.
Old question but I faced this same problem in my application, how to search through the hierarchical tree nodes.
I would like to share one correction to previous solutions proposal. When calling FindNodeRecursive() recursively the return value of your recursive call is never being evaluated or assigned to a variable. So, you will always end up with going through the foreach loop and return value is null.
Corrected and tested function code (WPF C#):
RadTreeNode FindNodeRecursive(RadTreeNodeCollection nodes, string value)
{
RadTreeNode ret = null;
foreach (RadTreeNode node in nodes)
{
if(node.Value == value)
return node;
if (node.Nodes.Count > 0)
{
ret = FindNodeRecursive(node.Nodes, value);
}
return ret;
}
}
Function use:
var node = FindNodeRecursive(PagesTreeView.Nodes, i.ToString());
if (node != null) // found
{
;
}

Efficient implementation of immutable (double) LinkedList

Having read this question Immutable or not immutable? and reading answers to my previous questions on immutability, I am still a bit puzzled about efficient implementation of simple LinkedList that is immutable. In terms of array tha seems to be easy - copy the array and return new structure based on that copy.
Supposedly we have a general class of Node:
class Node{
private Object value;
private Node next;
}
And class LinkedList based on the above allowing the user to add, remove etc. Now, how would we ensure immutability? Should we recursively copy all the references to the list when we insert an element?
I am also curious about answers in Immutable or not immutable? that mention cerain optimization leading to log(n) time and space with a help of a binary tree. Also, I read somewhere that adding an elem to the front is 0(1) as well. This puzzles me greatly, as if we don't provide the copy of the references, then in reality we are modifying the same data structures in two different sources, which breaks immutability...
Would any of your answers alo work on doubly-linked lists? I look forward to any replies/pointers to any other questions/solution. Thanks in advance for your help.
Supposedly we have a general class of Node and class LinkedList based on the above allowing the user to add, remove etc. Now, how would we ensure immutability?
You ensure immutability by making every field of the object readonly, and ensuring that every object referred to by one of those readonly fields is also an immutable object. If the fields are all readonly and only refer to other immutable data, then clearly the object will be immutable!
Should we recursively copy all the references to the list when we insert an element?
You could. The distinction you are getting at here is the difference between immutable and persistent. An immutable data structure cannot be changed. A persistent data structure takes advantage of the fact that a data structure is immutable in order to re-use its parts.
A persistent immutable linked list is particularly easy:
abstract class ImmutableList
{
public static readonly ImmutableList Empty = new EmptyList();
private ImmutableList() {}
public abstract int Head { get; }
public abstract ImmutableList Tail { get; }
public abstract bool IsEmpty { get; }
public abstract ImmutableList Add(int head);
private sealed class EmptyList : ImmutableList
{
public override int Head { get { throw new Exception(); } }
public override ImmutableList Tail { get { throw new Exception(); } }
public override bool IsEmpty { get { return true; } }
public override ImmutableList Add(int head)
{
return new List(head, this);
}
}
private sealed class List : ImmutableList
{
private readonly int head;
private readonly ImmutableList tail;
public override int Head { get { return head; } }
public override ImmutableList Tail { get { return tail; } }
public override bool IsEmpty { get { return false; } }
public override ImmutableList Add(int head)
{
return new List(head, this);
}
}
}
...
ImmutableList list1 = ImmutableList.Empty;
ImmutableList list2 = list1.Add(100);
ImmutableList list3 = list2.Add(400);
And there you go. Of course you would want to add better exception handling and more methods, like IEnumerable<int> methods. But there is a persistent immutable list. Every time you make a new list, you re-use the contents of an existing immutable list; list3 re-uses the contents of list2, which it can do safely because list2 is never going to change.
Would any of your answers also work on doubly-linked lists?
You can of course easily make a doubly-linked list that does a full copy of the entire data structure every time, but that would be dumb; you might as well just use an array and copy the entire array.
Making a persistent doubly-linked list is quite difficult but there are ways to do it. What I would do is approach the problem from the other direction. Rather than saying "can I make a persistent doubly-linked list?" ask yourself "what are the properties of a doubly-linked list that I find attractive?" List those properties and then see if you can come up with a persistent data structure that has those properties.
For example, if the property you like is that doubly-linked lists can be cheaply extended from either end, cheaply broken in half into two lists, and two lists can be cheaply concatenated together, then the persistent structure you want is an immutable catenable deque, not a doubly-linked list. I give an example of a immutable non-catenable deque here:
http://blogs.msdn.com/b/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx
Extending it to be a catenable deque is left as an exercise; the paper I link to on finger trees is a good one to read.
UPDATE:
according to the above we need to copy prefix up to the insertion point. By logic of immutability, if w delete anything from the prefix, we get a new list as well as in the suffix... Why to copy only prefix then, and not suffix?
Well consider an example. What if we have the list (10, 20, 30, 40), and we want to insert 25 at position 2? So we want (10, 20, 25, 30, 40).
What parts can we reuse? The tails we have in hand are (20, 30, 40), (30, 40) and (40). Clearly we can re-use (30, 40).
Drawing a diagram might help. We have:
10 ----> 20 ----> 30 -----> 40 -----> Empty
and we want
10 ----> 20 ----> 25 -----> 30 -----> 40 -----> Empty
so let's make
| 10 ----> 20 --------------> 30 -----> 40 -----> Empty
| /
| 10 ----> 20 ----> 25 -/
We can re-use (30, 40) because that part is in common to both lists.
UPDATE:
Would it be possible to provide the code for random insertion and deletion as well?
Here's a recursive solution:
ImmutableList InsertAt(int value, int position)
{
if (position < 0)
throw new Exception();
else if (position == 0)
return this.Add(value);
else
return tail.InsertAt(value, position - 1).Add(head);
}
Do you see why this works?
Now as an exercise, write a recursive DeleteAt.
Now, as an exercise, write a non-recursive InsertAt and DeleteAt. Remember, you have an immutable linked list at your disposal, so you can use one in your iterative solution!
Should we recursively copy all the references to the list when we insert an element?
You should recursively copy the prefix of the list up until the insertion point, yes.
That means that insertion into an immutable linked list is O(n). (As is inserting (not overwriting) an element in array).
For this reason insertion is usually frowned upon (along with appending and concatenation).
The usual operation on immutable linked lists is "cons", i.e. appending an element at the start, which is O(1).
You can see clearly the complexity in e.g. a Haskell implementation. Given a linked list defined as a recursive type:
data List a = Empty | Node a (List a)
we can define "cons" (inserting an element at the front) directly as:
cons a xs = Node a xs
Clearly an O(1) operation. While insertion must be defined recursively -- by finding the insertion point. Breaking the list into a prefix (copied), and sharing that with the new node and a reference to the (immutable) tail.
The important thing to remember about linked lists is :
linear access
For immutable lists this means:
copying the prefix of a list
sharing the tail.
If you are frequently inserting new elements, a log-based structure , such as a tree, is preferred.
There is a way to emulate "mutation" : using immutable maps.
For a linked list of Strings (in Scala style pseudocode):
case class ListItem(s:String, id:UUID, nextID: UUID)
then the ListItems can be stored in a map where the key is UUID:
type MyList = Map[UUID, ListItem]
If I want to insert a new ListItem into val list : MyList :
def insertAfter(l:MyList, e:ListItem)={
val beforeE=l.getElementBefore(e)
val afterE=l.getElementAfter(e)
val eToInsert=e.copy(nextID=afterE.nextID)
val beforeE_new=beforeE.copy(nextID=e.nextID)
val l_tmp=l.update(beforeE.id,beforeE_new)
return l_tmp.add(eToInsert)
}
Where add, update, get takes constant time using Map: http://docs.scala-lang.org/overviews/collections/performance-characteristics
Implementing double linked list goes similarly.

Print a simply linked list backwards with no recursion, in two passes at most, using constant extra memory, leaving it intact

You must print a simply linked list backwards:
Without recursion
With constant extra memory
In linear time
Leaving the list intact
Added Later Two passes at most
Invert the list, print it forwards, invert again. Each step can be done without violating restrictions except the last one.
EDIT: As cube notes in the comments the second and the third stages can be combined into one pass. This gives two passes – first reverse, then print while reversing again.
Building on sharptooth's reply, you can combine the printing and second inversion in the same pass.
Edit: The "list is left intact" from a single-threaded view because the post-condition equals the pre-condition.
Edit 2: Not sure how I got the answer, but I'll take it since I've hit the rep cap for the day. I gave sharptooth a +1 too.
Here's a C# implementation that holds for all the current rules. It mutates the list during the execution, but the list is restored before returning.
using System;
using System.Diagnostics;
namespace SO1135917.Classes
{
public class ReverseListPrinter
{
public static void Execute(Node firstNode, Action<Node> action)
{
Reverse(Reverse(firstNode, null), action);
}
private static Node Reverse(Node firstNode, Action<Node> action)
{
Node node = firstNode;
Debug.Assert(node != null);
Node nextNode = node.Next;
node.Next = null;
while (node != null)
{
if (action != null)
action(node);
if (nextNode == null)
break;
Node nextNode2 = nextNode.Next;
nextNode.Next = node;
node = nextNode;
nextNode = nextNode2;
}
return node;
}
}
}
There is one problem, however, and that is that the state of the list is undefined if an exception should occur in the above methods. Probably not impossible to handle though.
A subversion repository of the above code, with unit tests, for Visual Studio 2008 is available here, username and password is both 'guest' without the quotes.
You can first check the length of the list. Then create a print-buffer, which you fill in backwards as you traverse the list once again for the information.
Or
You can create another linked list where you add all the printing data in the front when you traverse the first list, and then print the second list from front to back.
Either way makes only two passes at most. The first idea could be done in one pass if you have a header struct that keeps track of the amount of elements in the list.
Edit: I just realised that these ideas does not use constant memory.
The only way to do this sensibly seems to be Sharptooths reply, but that requires three passes.
a function like the following might solver your issue:
void invert_print(PtNo l){
PtNo ptaux = l;
PtNo last;
PtNo before;
while(ptaux != NULL){
last = ptaux;
ptaux = ptaux->next;
}
while(ptaux != last){
printf("%s\n", last->info.title);
ptaux = l;
before = last;
while(ptaux != before){
last = ptaux;
ptaux = ptaux->next;
}
}
}
you will need a structure like the following:
typedef struct InfoNo{
char title20];
}InfoNo;
typedef struct aPtNo{
struct InfoNo info;
struct aPtNo* nextx;
}*PtNo;
Objective-C Link class with reverse method:
Link.h
#import <Foundation/Foundation.h>
#interface Link : NSObject
#property(nonatomic) int value;
#property(nonatomic) Link *next;
- (Link*)reversedList;
#end
Link.m
#import "Link.h"
#implementation Link
- (Link*)reversedList {
Link* head;
Link *link = self;
while (link) {
// save reference to next link
Link *next = link.next;
// "insert" link at the head of the list
link.next = head;
head = link;
// continue processing the rest of the list
link = next;
}
return head;
}
#end

How does LINQ implement the SingleOrDefault() method?

How is the method SingleOrDefault() evaluated in LINQ? Does it use a Binary Search behind the scenes?
Better than attempting to explain in words, I thought I'd just post the exact code of implementation in the .NET Framework, retrieved using the Reflector program (and reformatted ever so slightly).
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
switch (list.Count)
{
case 0:
return default(TSource);
case 1:
return list[0];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
return default(TSource);
TSource current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
}
throw Error.MoreThanOneElement();
}
It's quite interesting to oberserve that an optimisation is made if the object is of type IList<T>, which seems quite sensible. It simply falls back to enumerating over the object otherwise if the object implements nothing more specific than IEnumerable<T>, and does so just how you'd expect.
Note that it can't use a binary search because the object doesn't necessarily represent a sorted collection. (In fact, in almost all usage cases, it won't.)
I would assume that it simply performs the query and if the result count is zero, it returns the default instance of the class. If the result count is one, it returns that instance, and if the result count is greater than one, it throws an exception.
I don't think it does any searching, it's all about getting the first element of the source [list, result set, etc].
My best guess is that it just pulls the first element. If there is no first it returns the default (null, 0, false, etc). If there is a first, it attempts to pull the second result. If there is a second result it throws an exception. Otherwise it returns the first result.

Resources