473,769 Members | 6,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

please give me logic of how to sort link list of string

how to sort link list of string

Nov 20 '06 #1
9 4446
incredible said:
how to sort link list of string
Presumably you know that sorting consists of putting items into a particular
order, which implies that you need to be able to compare them and decide
which of them belongs earlier in the order. You also need to be able to
swap strings round if they're not in the right order. Presumably you know
how to compare two strings. So your immediate problem is: "how do I
exchange two items in a linked list?"

Assuming your nodes are defined like this:

struct node
{
struct node *prev;
struct node *next;
void *data;
};

(with the data pointer pointing to some kind of aggregate containing the key
data and perhaps a payload), it's very easy to swap two nodes:

if(p1 != NULL && p2 != NULL)
{
void *tmp = p1->data;
p1->data = p2->data;
p2->data = tmp;
}

If the data is *only* a string, s/void/char/

If you're using ordinary arrays in your nodes, though, it's slightly more
annoying, in that you'll have to get an array big enough to hold the
largest string in the list, and use that as your tmp, using strcpy rather
than assignment.

Once you've got that in place, it's just a matter of doing the right
compares and the right swaps in the right order.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: normal service will be restored as soon as possible. Please do not
adjust your email clients.
Nov 20 '06 #2
"incredible " <in************ **@yahoo.comwri tes:
how to sort link list of string
There's a pair of fairly complete and fairly portable linked list
libraries here:
http://cvs.savannah.gnu.org/viewcvs/...spp/?root=pspp
Look at ll.[ch] and llx.[ch].
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 20 '06 #3


incredible wrote On 11/20/06 12:05,:
how to sort link list of string
/* Usage instructions: Declare a `struct node' type containing a
* `struct node*' field named `next' as its forward link, along with
* whatever other elements are desired. Define a precedes() function
* that takes two `const struct node*' pointers and returns nonzero
* if the first struct must precede the second in the sorted output,
* or zero if the first follows the second or if they compare equal.
* Build a linked list of `struct node' instances, with the `next'
* field of the last node equal to NULL. Call the listsort() function,
* passing a pointer to the first node as the argument. listsort()
* will rearrange the list's links to sort the list in accordance with
* the precedes() function, and will return a pointer to the first
* `struct node' of the sorted list.
*
* Note: This code uses an OO style.
*/

#include <limits.h>
static struct node*O(struct node*o,struct node*O){struct node*Oo,**oO;
oO=&Oo;for(;;){ if(precedes(O,o )){*oO=O;oO=&O->next;if(0==(O= O->next)){
*oO=o;break;}}e lse{*oO=o;oO=&o->next;if(!(o= o->next)){*oO=O;b reak;}}}\
return Oo;}struct node*listsort(s truct node*oO){struct node*o,*o0[siz\
eof(void*)*CHAR _BIT-sizeof(char)],*Oo;int oo,O0;o0[O0=0]=0;while((o=o\
O)){if((Oo=o->next)==0)break ;oO=Oo->next;if(preced es(Oo,o)){Oo->next=o
;o->next=0;o=Oo;}e lse{Oo->next=0;}for(oo =0;(Oo=o0[oo]);){o0[oo]=0;o=O(
Oo,o);if(++oo>O 0){O0=oo;break; }}o0[oo]=o;}for(oo=0;oo <=O0;++oo){if(( o=
o0[oo]))oO=oO?O(o,oO) :o;}return oO;}

--
Er*********@sun .com

Nov 20 '06 #4
Eric Sosman skrev:
* Note: This code uses an OO style.
ROFL!

--
Tor

Nov 20 '06 #5
Eric Sosman wrote:
incredible wrote On 11/20/06 12:05,:
>how to sort link list of string

/* Usage instructions: Declare a `struct node' type containing a
* `struct node*' field named `next' as its forward link, along with
* whatever other elements are desired. Define a precedes() function
* that takes two `const struct node*' pointers and returns nonzero
* if the first struct must precede the second in the sorted output,
* or zero if the first follows the second or if they compare equal.
* Build a linked list of `struct node' instances, with the `next'
* field of the last node equal to NULL. Call the listsort() function,
* passing a pointer to the first node as the argument. listsort()
* will rearrange the list's links to sort the list in accordance with
* the precedes() function, and will return a pointer to the first
* `struct node' of the sorted list.
*
* Note: This code uses an OO style.
*/

#include <limits.h>
static struct node*O(struct node*o,struct node*O){struct node*Oo,**oO;
oO=&Oo;for(;;){ if(precedes(O,o )){*oO=O;oO=&O->next;if(0==(O= O->next)){
*oO=o;break;}}e lse{*oO=o;oO=&o->next;if(!(o= o->next)){*oO=O;b reak;}}}\
return Oo;}struct node*listsort(s truct node*oO){struct node*o,*o0[siz\
eof(void*)*CHAR _BIT-sizeof(char)],*Oo;int oo,O0;o0[O0=0]=0;while((o=o\
O)){if((Oo=o->next)==0)break ;oO=Oo->next;if(preced es(Oo,o)){Oo->next=o
;o->next=0;o=Oo;}e lse{Oo->next=0;}for(oo =0;(Oo=o0[oo]);){o0[oo]=0;o=O(
Oo,o);if(++oo>O 0){O0=oo;break; }}o0[oo]=o;}for(oo=0;oo <=O0;++oo){if(( o=
o0[oo]))oO=oO?O(o,oO) :o;}return oO;}
[1] c:\c\junk>cc junk.c
junk.c: In function `O':
junk.c:3: warning: implicit declaration of function `precedes'
junk.c:3: dereferencing pointer to incomplete type
junk.c:3: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c: In function `listsort':
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:8: dereferencing pointer to incomplete type
junk.c:8: dereferencing pointer to incomplete type

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 20 '06 #6


CBFalconer wrote On 11/20/06 16:06,:
Eric Sosman wrote:
>>incredible wrote On 11/20/06 12:05,:

>>>how to sort link list of string

/* Usage instructions: Declare a `struct node' type containing a
* `struct node*' field named `next' as its forward link, along with
* whatever other elements are desired. Define a precedes() function
* that takes two `const struct node*' pointers and returns nonzero
* if the first struct must precede the second in the sorted output,
* or zero if the first follows the second or if they compare equal.
* Build a linked list of `struct node' instances, with the `next'
* field of the last node equal to NULL. Call the listsort() function,
* passing a pointer to the first node as the argument. listsort()
* will rearrange the list's links to sort the list in accordance with
* the precedes() function, and will return a pointer to the first
* `struct node' of the sorted list.
*
* Note: This code uses an OO style.
*/

#include <limits.h>
static struct node*O(struct node*o,struct node*O){struct node*Oo,**oO;
oO=&Oo;for(;; ){if(precedes(O ,o)){*oO=O;oO=& O->next;if(0==(O= O->next)){
*oO=o;break;} }else{*oO=o;oO= &o->next;if(!(o= o->next)){*oO=O;b reak;}}}\
return Oo;}struct node*listsort(s truct node*oO){struct node*o,*o0[siz\
eof(void*)*CH AR_BIT-sizeof(char)],*Oo;int oo,O0;o0[O0=0]=0;while((o=o\
O)){if((Oo= o->next)==0)break ;oO=Oo->next;if(preced es(Oo,o)){Oo->next=o
;o->next=0;o=Oo;}e lse{Oo->next=0;}for(oo =0;(Oo=o0[oo]);){o0[oo]=0;o=O(
Oo,o);if(++oo >O0){O0=oo;brea k;}}o0[oo]=o;}for(oo=0;oo <=O0;++oo){if(( o=
o0[oo]))oO=oO?O(o,oO) :o;}return oO;}


[1] c:\c\junk>cc junk.c
junk.c: In function `O':
junk.c:3: warning: implicit declaration of function `precedes'
junk.c:3: dereferencing pointer to incomplete type
junk.c:3: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c: In function `listsort':
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:4: dereferencing pointer to incomplete type
junk.c:8: dereferencing pointer to incomplete type
junk.c:8: dereferencing pointer to incomplete type
Looks like you failed to heed the usage instructions.

--
Er*********@sun .com

Nov 20 '06 #7
incredible wrote:
>
how to sort link list of string
/* BEGIN new.c output */

Original order of list:
one
two
three
four
five
six
seven
eight
nine
ten

List after stable mergesort by string length:
one
two
six
ten
four
five
nine
three
seven
eight

The list has been freed.

/* END new.c output */
/* BEGIN new.c */

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

#define NMEMB(A) (sizeof (A) / sizeof *(A))

struct list_node {
struct list_node *next;
void *data;
};

typedef struct list_node list_type;

void list_free(list_ type *node, void (*free_data)(vo id *));
void list_fputs(FILE *stream, list_type *node);
list_type *string_node(li st_type **head,
list_type *tail,
char *data);
int lencomp(const void *a, const void *b);
list_type *list_sort(list _type *head,
int (*compar)(const list_type *, const list_type *));
static int list_sorted(lis t_type *list,
int (*compar)(const list_type *, const list_type *));
static long unsigned node_count(list _type *head);
static list_type *node_sort(list _type *head, long unsigned count,
int (*compar)(const list_type *, const list_type *));
static list_type *list_split(lis t_type *head, long unsigned count);
static list_type *list_merge(lis t_type *head, list_type *tail,
int (*compar)(const list_type *, const list_type *));

int main(void)
{
char *string[] = {
"one","two","th ree","four","fi ve",
"six","seven"," eight","nine"," ten"
};
list_type *head, *tail;
unsigned index;

tail = head = NULL;
index = 0;
do {
tail = string_node(&he ad, tail, string[index]);
} while (tail != NULL && ++index != NMEMB(string));
if (tail == NULL) {
list_free(head, free);
puts("malloc trouble!");
exit(EXIT_FAILU RE);
}
puts("/* BEGIN new.c output */\n");
puts("Original order of list:");
list_fputs(stdo ut, head);
head = list_sort(head, lencomp);
puts("\nList after stable mergesort by string length:");
list_fputs(stdo ut, head);
list_free(head, free);
puts("\nThe list has been freed.\n");
puts("/* END new.c output */");
return 0;
}

void list_free(list_ type *node, void (*free_data)(vo id *))
{
list_type *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

void list_fputs(FILE *stream, list_type *node)
{
while (node != NULL) {
fputs(node -data, stream);
putc('\n', stream);
node = node -next;
}
}

list_type *string_node(li st_type **head,
list_type *tail,
char *data)
{
list_type *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(strlen(d ata) + 1);
if (node -data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -next = node;
}
strcpy(node -data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

int lencomp(const void *a, const void *b)
{
const size_t a_len = strlen(((const list_type *)a) -data);
const size_t b_len = strlen(((const list_type *)b) -data);

return b_len a_len ? -1 : a_len != b_len;
}

list_type *list_sort(list _type *head,
int (*compar)(const list_type *, const list_type *))
{
return
!list_sorted(he ad, compar)
? node_sort(head, node_count(head ), compar)
: head;
}

static int list_sorted(lis t_type *list,
int (*compar)(const list_type *, const list_type *))
{
if (list != NULL) {
while (list -next != NULL) {
if (compar(list, list -next) 0) {
break;
}
list = list -next;
}
}
return list == NULL || list -next == NULL;
}

static long unsigned node_count(list _type *head)
{
long unsigned count;

for (count = 0; head != NULL; head = head -next) {
++count;
}
return count;
}

static list_type *node_sort(list _type *head, long unsigned count,
int (*compar)(const list_type *, const list_type *))
{
long unsigned half;
list_type *tail;

if (count 1) {
half = count / 2;
tail = list_split(head , half);
tail = node_sort(tail, count - half, compar);
head = node_sort(head, half, compar);
head = list_merge(head , tail, compar);
}
return head;
}

static list_type *list_split(lis t_type *head, long unsigned count)
{
list_type *tail;

while (--count != 0) {
head = head -next;
}
tail = head -next;
head -next = NULL;
return tail;
}

static list_type *list_merge(lis t_type *head, list_type *tail,
int (*compar)(const list_type *, const list_type *))
{
list_type *list, *sorted, **node;

node = compar(head, tail) 0 ? &tail : &head;
sorted = list = *node;
*node = sorted -next;
while (*node != NULL) {
node = compar(head, tail) 0 ? &tail : &head;
sorted -next = *node;
sorted = *node;
*node = sorted -next;
}
sorted -next = head != NULL ? head : tail;
return list;
}

/* END new.c */
--
pete
Nov 21 '06 #8
incredible wrote:
>
how to sort link list of string
/* Sort file stdin. By C.B. Falconer, 20 Nov. 2006 */
/* Released to public domain. Attribution appreciated */
/* Run with "sortfile < whatever" */

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

typedef struct line {
char *ln;
struct line *next;
} line, *lineptr;

/* ------------------------- */

#define INITSIZE 112
#define DELTASIZE (INITSIZE + 16)

enum {OK = 0, NOMEM};

/* See published ggets.zip */
int ggets(char* *ln)
{
int cursize, ch, ix;
char *buffer, *temp;

*ln = NULL; /* default */
if (NULL == (buffer = malloc(INITSIZE ))) return NOMEM;
cursize = INITSIZE;

ix = 0;
while ((EOF != (ch = getc(stdin))) && ('\n' != ch)) {
if (ix >= (cursize - 1)) { /* extend buffer */
cursize += DELTASIZE;
if (NULL == (temp = realloc(buffer, (size_t)cursize ))) {
/* ran out of memory, return partial line */
buffer[ix] = '\0';
*ln = buffer;
return NOMEM;
}
buffer = temp;
}
buffer[ix++] = ch;
}
if ((EOF == ch) && (0 == ix)) {
free(buffer);
return EOF;
}

buffer[ix] = '\0';
if (NULL == (temp = realloc(buffer, (size_t)ix + 1))) {
*ln = buffer; /* without reducing it */
}
else *ln = temp;
return OK;
} /* ggets */

/* ------------------------- */

/* split list p into 2 nearly equal lists, return 2nd part */
static lineptr splitlist(linep tr p)
{
lineptr p1, p2, p3;

p1 = p2 = p3 = p;
if (!p) return NULL;
do {
p3 = p2;
p2 = p2->next; /* advance 1 */
p1 = p1->next;
if (p1) p1 = p1->next; /* advance 2 */
} while (p1);

/* now form new list after p2 */
p3->next = NULL; /* terminate 1st half */
return p2;
} /* splitlist */

/* ------------------------- */

/* Merge two ordered lists into one */
static lineptr mergelists(line ptr p1, lineptr p2)
{
line n;
lineptr p;

p = &n;
n.next = p;

while (p1 && p2) {
if (strcmp(p1->ln, p2->ln) <= 0) {
p->next = p1; p = p1; p1 = p1->next;
}
else {
p->next = p2; p = p2; p2 = p2->next;
}
}
/* at least one list now empty, copy other */
/* one or both of these operations is null */
if (p1) p->next = p1;
if (p2) p->next = p2;

/* check for empty lists */
if (n.next == &n) return NULL;
return n.next;
} /* mergelists */

/* ------------------------- */

/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
static lineptr mergesort(linep tr root)
{
lineptr p;

if (root && root->next) { /* 2 up items in list */
p = splitlist(root) ; /* alters list root */
root = mergelists(merg esort(root),
mergesort( p));
}
/* else the unit or empty list is already sorted */

return root;
} /* mergesort */

/* ------------------------- */

/* Load, sort, and print file, which fits in memory. */
int main(void)
{
lineptr p, last;
char *nextln;

p = NULL;
while (0 == ggets(&nextln))
if ((last = malloc(sizeof *last))) {
last->ln = nextln;
last->next = p;
p = last;
}
else break; /* out of memory or i/o error */

p = mergesort(p);

while (p) {
puts(p->ln);
last = p;
p = p->next;
free(last->ln);
free(last);
}
return 0;
} /* sortfile main */

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 21 '06 #9
pete wrote:
list_type *list_sort(list _type *head,
int (*compar)(const list_type *, const list_type *));
head = list_sort(head, lencomp);
int lencomp(const void *a, const void *b)
{
const size_t a_len = strlen(((const list_type *)a) -data);
const size_t b_len = strlen(((const list_type *)b) -data);

return b_len a_len ? -1 : a_len != b_len;
}
That function's prototype should be
int lencomp(const list_type *a, const list_type *b);
and the definition should be:

int lencomp(const list_type *a, const list_type *b)
{
const size_t a_len = strlen(a -data);
const size_t b_len = strlen(b -data);

return b_len a_len ? -1 : a_len != b_len;
}

instead.

--
pete
Nov 21 '06 #10

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

Similar topics

3
1591
by: Mike | last post by:
Hey guys I am pulling my hair out on this problem!!!!! Any help or ideas or comments on how to make this work I would be grateful! I have been working on this for the past 4 days and nothing I do seems to get me any closer to the solution. Below is a program that I am working on for a class project. The original code was provided for us which is what I have below. What we have to do is make the app run so that it allows the user to add...
7
2172
by: Stephen | last post by:
I have some code which I call from a custom validator however I seem to have got the logic wrong and im having trouble figuring out how to write my code to get things to work the way I require. Below is the script I currently use and what it does along with what I would like it to do. Can someone please help me work how I can fix this. <script> function ValidateDropDownOrCheckBox(sender, args) { if ( document.forms.DropDownList1.value...
1
1692
by: Jason | last post by:
I've gathered a bunch of data from Active Directory and placed it into a datatable ("ADTable"). I now need to sort and filter this table based on the selection of a drop down list("ddlCategory"). How can I filter the dataview of this datatable to display those records that match (partially or fully) the value selected in the drop down list? I have the following code that doesn't work, and returns zero rows (note that 'department' is a...
1
9651
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej and I was wondering if anyone here would be able to give me some tips for young players such as myself, for learning the language. Is this the best Newsgroup for support with JAVA?
48
4491
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a lot faster with both methods using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below you can find C# test case that should allow you to reproduce this error, to run it you will need to put 2 data files into current directory...
2
1796
by: incredible | last post by:
how to merge two sorted link list
1
2441
by: alivip | last post by:
I integrat program to be GUI using Tkinter I try browser direction as you can see # a look at the Tkinter Text widget # use ctrl+c to copy, ctrl+x to cut selected text, # ctrl+v to paste, and ctrl+/ to select all # count words in a text and show the first ten items
5
2540
by: alivip | last post by:
How can I get every Token (word) and PreviousToken(Previous word) From multube files and frequency of each two word my code is trying to get all single word and double word (every Token (word) and PreviousToken(Previous word)) from multube files and get frequency of both. it can get for single word but double word give error line 50, in most_frequant_word word1+= ' ' + word_list IndexError: list index out of range import...
3
1760
by: BlueroY | last post by:
hi, I'm working on an exercise, i did a lot of work already and i just can't figure where I'm going wrong, this is what I'm trying to achieve Sample IO ******************************************************************************* Welcome to PeopleSoft 2 MENU: (A)dd student, (D)elete, (L)ist, (S)ort, e(X)it a Enter the student number MSXMIC001 Enter the name
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10216
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.