473,386 Members | 1,621 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Memmove v/s Linked list Implementation

Hello there my friends, this is my first attempt at posting in a
newsgroup. Here is my problem statement:

Me and my friend decided to solve a programming problem with our own
styles and then decide which one is the best. The problem being:
"Remove all occurrences of a character (case insensitive) from a given
string"
eg.
i/p: She will be a massless princess
o/p: he will be a male prince (all occurances of 's' removed)

My friend implemented the solution by creating a Linked List of all the
character in which each node holds one character !!! Here is his code:

#include<stdio.h>
# include <iostream>
# include <conio.h>
using namespace std;

typedef struct charNode
{
char ch;
charNode* nxt;
charNode(char ch1 = 0){
nxt = NULL;
ch = ch1;
}
}cn;

int main()
{
cn* head = NULL,* temp, *node;
char ch1 = 'e', ch2;// ch1 is to hold the char that is to be
elimintated and ch2 to temp store the char

cout<< "enter string " ;
head = new cn ();
node = head;

ch2 = cin.get();
while ( ch2 != 10) { // this while loop for creating SLL
temp = new cn(ch2) ;
node->nxt = temp;
node = node->nxt;
ch2 = cin.get();
}

node = head; // for removal of unwanted character ... this
character given by ch1
while (node->nxt != NULL) {
if ( node->nxt->ch == ch1 ) {
temp = node->nxt;
if( temp->nxt == NULL )
node->nxt = NULL;
else
node->nxt = node->nxt->nxt;
delete temp;
}
else
node = node->nxt;
}

node = head; // display the elements !
while ( node -nxt != NULL ) {
cout<<node->ch;
node = node->nxt;
}
cout<<node->ch;
getchar();
return 0;
}

Whereas I implemented the solution using memmove, ie shifting the
entire string when the character to be eliminated is encountered. Here
is my effort:

#include <stdio.h>
#include <string.h>
const char chUpper = 'S' ;
const char chLower = 's' ;

void remove_s( char tmp[] )
{
while( *tmp != '\0' )
{
if( *tmp == chLower || *tmp == chUpper )
{
memmove( tmp, tmp + 1, &tmp[strlen( tmp )] - tmp ) ;
}
else
{
tmp++ ;
}
}
}

int main( )
{
char str[] = " Asser is an asser and nothing but asser, so be
solemsn " ;
printf( "\nThe old string: %s", str ) ;
remove_s( str ) ;
printf( "\nThe new string: %s", str ) ;

getchar( ) ;
return (0);
}

Now the problem is, we can't get to decide which piece of code is more
computationally expensive and would start giving problems as the length
of the string increases.....

Your expert views or any other efficient implementation is appreciated.
Also it would be really nice if you could point out the problem areas
in mine or his code....

Thanks again...

Jan 23 '07 #1
15 3397

ge**************@gmail.com wrote:
Hello there my friends, this is my first attempt at posting in a
newsgroup. Here is my problem statement:

Me and my friend decided to solve a programming problem with our own
styles and then decide which one is the best. The problem being:
"Remove all occurrences of a character (case insensitive) from a given
string"
eg.
i/p: She will be a massless princess
o/p: he will be a male prince (all occurances of 's' removed)

My friend implemented the solution by creating a Linked List of all the
character in which each node holds one character !!! Here is his code:

#include<stdio.h>
# include <iostream>
# include <conio.h>
using namespace std;
Please post C++ code to comp.lang.c++. Also read the FAQ for this group
from c-faq.com.
Now the problem is, we can't get to decide which piece of code is more
computationally expensive and would start giving problems as the length
of the string increases.....
Both methods are arguably overkill for the specification as you've
stated above.

Jan 23 '07 #2
ge**************@gmail.com writes:
Hello there my friends, this is my first attempt at posting in a
newsgroup.
You picked the wrong one. Your programs are written in C++, but
you posted to comp.lang.c. Furthermore, you really have an
algorithms question, but comp.lang.c is not about algorithms.
Me and my friend decided to solve a programming problem with our own
styles and then decide which one is the best. The problem being:
"Remove all occurrences of a character (case insensitive) from a given
string"
eg.
i/p: She will be a massless princess
o/p: he will be a male prince (all occurances of 's' removed)

My friend implemented the solution by creating a Linked List of all the
character in which each node holds one character !!! Here is his code:
[...]
Whereas I implemented the solution using memmove, ie shifting the
entire string when the character to be eliminated is encountered. Here
is my effort:
[...]
Now the problem is, we can't get to decide which piece of code is more
computationally expensive and would start giving problems as the length
of the string increases.....
A linked list solution could take O(N) time and space, but moving
the entire rest of the string around for each "s" encountered
takes O(N**2) time and O(N) space.

Here is a better solution (although I haven't tested it):

/* Remove all the "s" characters from STRING, in-place. */
void
remove_s (char *string)
{
char *p = string;
do {
if (*string != 's')
*p++ = *string;
} while (*string++ != '\0');
}
--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms
Jan 23 '07 #3
>Santosh wrote:
Please post C++ code to comp.lang.c++. Also read the FAQ for this group
from c-faq.com.
But since my program was in C I thought this would be a better place.
Don't you think that if I posted in the comp.langauge.c++ group, they
would say the same thing to me since my code in in C and my friends in
C++ ?
Ben Pfaff wrote:
You picked the wrong one. Your programs are written in C++, but
you posted to comp.lang.c. Furthermore, you really have an
algorithms question, but comp.lang.c is not about algorithms.
Is there any algorithms newsgroup ? BTW my code is in C and my friends
in C++.
A linked list solution could take O(N) time and space, but moving
the entire rest of the string around for each "s" encountered
takes O(N**2) time and O(N) space.
So I guess it means that the memmove is after all more expensive than
the Linked List one...But I thought the memmove in C was implemented in
Assembly and moving around chunks of raw data would be as fast as it
got in C ?

Jan 23 '07 #4
ge**************@gmail.com writes:
Ben Pfaff wrote:
>You picked the wrong one. Your programs are written in C++, but
you posted to comp.lang.c. Furthermore, you really have an
algorithms question, but comp.lang.c is not about algorithms.

Is there any algorithms newsgroup ? BTW my code is in C and my friends
in C++.
I'd suggest comp.programming.
>A linked list solution could take O(N) time and space, but moving
the entire rest of the string around for each "s" encountered
takes O(N**2) time and O(N) space.

So I guess it means that the memmove is after all more expensive than
the Linked List one...But I thought the memmove in C was implemented in
Assembly and moving around chunks of raw data would be as fast as it
got in C ?
Suppose that the string consists entirely of "s"es. Then your
implementation will copy N + (N-1) + (N-2) + ... + 2 + 1 bytes,
or approximately (N**2)/2 bytes. My implementation will copy 1
byte (the null terminator). Do you still think yours should be
faster?
--
"For those who want to translate C to Pascal, it may be that a lobotomy
serves your needs better." --M. Ambuhl

"Here are the steps to create a C-to-Turbo-Pascal translator..." --H. Schildt
Jan 23 '07 #5
ge**************@gmail.com wrote:
Santosh wrote:
Please post C++ code to comp.lang.c++. Also read the FAQ for this group
from c-faq.com.

But since my program was in C I thought this would be a better place.
Don't you think that if I posted in the comp.langauge.c++ group, they
would say the same thing to me since my code in in C and my friends in
C++ ?
Since C, is for practical purposes, a subset of C++, comp.lang.c++
would be a better place than here. The best solution, of course, is to
have both your examples in a single language, or post to a more
algorithm centric group like comp.programming.
Ben Pfaff wrote:
You picked the wrong one. Your programs are written in C++, but
you posted to comp.lang.c. Furthermore, you really have an
algorithms question, but comp.lang.c is not about algorithms.

Is there any algorithms newsgroup ? BTW my code is in C and my friends
in C++.
comp.programming is one.
A linked list solution could take O(N) time and space, but moving
the entire rest of the string around for each "s" encountered
takes O(N**2) time and O(N) space.

So I guess it means that the memmove is after all more expensive than
the Linked List one...But I thought the memmove in C was implemented in
Assembly and moving around chunks of raw data would be as fast as it
got in C ?
This has nothing to do with the implementation. Even the fastest
assembly code will be of no use to you, if you picked the wrong high
level algorithm to begin with. As I said, for the problem as you state
above, which is very simple, both the solutions are overkill, the
memmove() based one, especially so. Ben Pfaff's solution is a good
alternative.

Jan 23 '07 #6

@ Santosh and Ben
Thanks both of you for the newsgroup name...

@Ben:
Yeah I do realize that in whatever way the memmove be internally
implemented, the way I have used it is really an overkill. If possible
Ben, can you please describe in detail what you said previously about
O(N**2) complexity in time and O(N) complexity in space regarding my
solution... ?

Jan 23 '07 #7
getsanjay.sha...@gmail.com wrote:
@ Santosh and Ben
Thanks both of you for the newsgroup name...

@Ben:
Yeah I do realize that in whatever way the memmove be internally
implemented, the way I have used it is really an overkill. If possible
Ben, can you please describe in detail what you said previously about
O(N**2) complexity in time and O(N) complexity in space regarding my
solution... ?
In the meanwhile, the following pages should give an introduction for
this notation:

<http://en.wikipedia.org/wiki/Big_O_notation>
<http://www.eecs.harvard.edu/~ellard/Q-97/HTML/root/node5.html>

Jan 23 '07 #8
ge**************@gmail.com wrote:
>
.... snip ...
>
The problem being: "Remove all occurrences of a character (case
insensitive) from a given string"
eg.
i/p: She will be a massless princess
o/p: he will be a male prince (all occurances of 's' removed)

My friend implemented the solution by creating a Linked List of all the
character in which each node holds one character !!! Here is his code:
.... snip 100 lines of ridiculously bloated off-topic C++ code
>
Now the problem is, we can't get to decide which piece of code is more
computationally expensive and would start giving problems as the length
of the string increases.....

Your expert views or any other efficient implementation is appreciated.
Also it would be really nice if you could point out the problem areas
in mine or his code....
#include <stdio.h>

int main(int argc, char **argv) {
int ch;

if (argc < 2) puts("Usage: junk c <input");
else
while (EOF != (ch = getchar()))
if (ch != *argv[1]) putchar(ch);
return 0;
}

c:\c\junk>cc junk.c
c:\c\junk>a s
She will be a massless princess
She will be a male prince

Maybe this will convince you that C++ is not appropriate for many
things.

--
Some informative links:
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html>
<http://www.netmeister.org/news/learn2quote.html>
<http://cfaj.freeshell.org/google/ (taming google)
<http://members.fortunecity.com/nnqweb/ (newusers)

Jan 23 '07 #9
>>>>"gs" == getsanjay sharma <ge**************@gmail.comwrites:

gsMe and my friend decided to solve a programming problem with
gsour own styles and then decide which one is the best. The
gsproblem being: "Remove all occurrences of a character (case
gsinsensitive) from a given string"

You both wrote some horrendously bad code. This (below) is optimized
for terseness, and has an additional feature that it will remove any
character, not just S.

#include <ctype.h>
#include <string.h>
#include <stdio.h>

char *remove_char (char *target, char ch)
{
char *src = target;
char *dst = target;

char lch = tolower(ch);
char sch;

while (sch = *src++)
if (tolower(sch) != lch)
*dst++ = sch;

*dst = 0;

return target;
}

int main (void)
{
char in[] = " Asser is an asser and nothing but asser, so be solemsn";
printf("The old string: %s\n", in);
remove_char (in, 's');
printf( "The new string: %s\n", in);

return 0;
}

(Of course, in Perl, I'd just say $str =~ s/s//gi; and call it good.)

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Jan 23 '07 #10
Thanks a lot all your guys for your valuable time and comments...

Charlton Wilbur wrote:
You both wrote some horrendously bad code.
Yes I know, I have already been clubbed by almost all the members
because of this... ;-)
(Of course, in Perl, I'd just say $str =~ s/s//gi; and call it good.)
Wish C was as forgiving as Perl...

Thanks again all of you. When I have a C doubt, I know where to turn
to.... :-D

Jan 24 '07 #11
<ge**************@gmail.comwrote in message
news:11**********************@h3g2000cwc.googlegro ups.com...
Now the problem is, we can't get to decide which piece of code is more
computationally expensive and would start giving problems as the length
of the string increases.....
Assuming uniform distribution of the characters to be removed, the memmove()
method is O(N**2). This comes about because each of the later characters in
the string may need to be moved many times.

Both methods you proposed suck from an efficiency point of view.

O(N**2) sucks very badly when O(N) is available.

The most efficient method--and it is O(N)--would be to maintain two pointers
within the string, one being the "put" point and the other being the "get"
point. Just skip the "get" pointer over the characters you don't want. For
all others, write them to the "put" pointer and advance it by one. The code
is so trivial I won't write it for a newsgroup post.

--
David T. Ashley (dt*@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Jan 24 '07 #12
"David T. Ashley" <dt*@e3ft.comwrites:
The most efficient method--and it is O(N)--would be to maintain two pointers
within the string, one being the "put" point and the other being the "get"
point. Just skip the "get" pointer over the characters you don't want. For
all others, write them to the "put" pointer and advance it by one. The code
is so trivial I won't write it for a newsgroup post.
For what it's worth, I already put code for this somewhere else
in the thread.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Jan 24 '07 #13
"santosh" <sa*********@gmail.comwrote in message
news:11*********************@13g2000cwe.googlegrou ps.com...
getsanjay.sha...@gmail.com wrote:
>Yeah I do realize that in whatever way the memmove be internally
implemented, the way I have used it is really an overkill. If
possible
Ben, can you please describe in detail what you said previously
about O(N**2) complexity in time and O(N) complexity in space
regarding my solution... ?

In the meanwhile, the following pages should give an introduction for
this notation:

<http://en.wikipedia.org/wiki/Big_O_notation>
<http://www.eecs.harvard.edu/~ellard/Q-97/HTML/root/node5.html>
Both good introductions, but one thing that both mostly neglect is that
they compare algorithms for _large_ values of N. Big-O notation drops
all the constants and non-dominant terms, and thus is not necessarily
helpful for small values of N. For instance, it isn't difficult to find
examples where an O(N^2) algorithm outperforms an O(N) one due to large
constants on the latter.

The end result is that the best solution for a string of 10 characters
may not be the best solution for a string of 10,000 characters and vice
versa.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 25 '07 #14
Ben Pfaff wrote:
"David T. Ashley" <dt*@e3ft.comwrites:
>The most efficient method--and it is O(N)--would be to maintain
two pointers within the string, one being the "put" point and the
other being the "get" point. Just skip the "get" pointer over
the characters you don't want. For all others, write them to the
"put" pointer and advance it by one. The code is so trivial
I won't write it for a newsgroup post.

For what it's worth, I already put code for this somewhere else
in the thread.
As did I, except I used i/o streams.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Jan 25 '07 #15
On Tue, 23 Jan 2007 17:12:16 -0500, CBFalconer <cb********@yahoo.comwrote:
ge**************@gmail.com wrote:
>>
... snip ...
>>
The problem being: "Remove all occurrences of a character (case
insensitive) from a given string"
eg.
i/p: She will be a massless princess
o/p: he will be a male prince (all occurances of 's' removed)

My friend implemented the solution by creating a Linked List of all the
character in which each node holds one character !!! Here is his code:
... snip 100 lines of ridiculously bloated off-topic C++ code
....
int main(int argc, char **argv) {
int ch;

if (argc < 2) puts("Usage: junk c <input");
else
while (EOF != (ch = getchar()))
if (ch != *argv[1]) putchar(ch);
Nitpick: you need a tolower() somewhere here to meet the requirements.
return 0;
}
....
Maybe this will convince you that C++ is not appropriate for many
things.
This is offtopic here, but the quoted (and thankfully, snipped) C++ code
was (again, thankfully) non-representative. The original poster's friend
needs to get a modern book on the subject. Badly. Hints: std::list,
std::string, std::copy_if.

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn!
Feb 1 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: George M Jempty | last post by:
Is there a good linked list implementation in the public domain? Or that someone on this group has already written that they'd like to put in the public domain, right here on this newsgroup? I've...
5
by: Darryl B | last post by:
I can not get anywhere on this project I'm tryin to do. I'm not expecting any major help with this but any would be appreciated. The assignment is attached. The problem I'm having is trying to set...
21
by: Method Man | last post by:
Just a few theoretical questions I had on 'memmove': 1. Is there ever a good reason to use memcpy instead of memmove? 2. Is memmove useful to copy structs (as opposed to = operator)? 3. In...
12
by: Ian | last post by:
I read the FAQ about the differences between memcpy() and memmove(). Apparently memmove() is supposed to be safer. Just to make sure I understand the concept of memmove(), can someone tell me if...
4
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event...
1
by: kyo guan | last post by:
Hi : python list object like a stl vector, if insert a object in the front or the middle of it, all the object after the insert point need to move backward. look at this code ( in python...
51
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort...
9
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node *...
8
by: Jeff Bown | last post by:
Consider implementing a (doubly) linked list. The simplest strategy is to provide functions item_t add_item(item_t predecessor); void delete_item(item_t item); where add_item allocates memory...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.