Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,111 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,727 people online right now. Registration is fast and FREE... Join Now!




Linked List (sorting)

 
Reply to this topicStart new topic

Linked List (sorting)

kkgaming
9 Apr, 2007 - 10:28 PM
Post #1

D.I.C Head
**

Joined: 7 Feb, 2007
Posts: 75


My Contributions
The purpose of this program is to take in base 21 numbers from an infile, and print them out sorted.
The one question I have is, how do I sort them without passing GetNode a 0.

My infile looks like this: (the first number is the list size)

10
BCD
J
ECDA
F
A
E
G
K
H
I


Here is the ouput to my program:

List size: 10
Inserting 19
Inserting 135229
Inserting 15
Inserting 10
Inserting 14
Inserting 16
Inserting 20
Inserting 17
Inserting 18
----- Sorted list -----
Val: 0
Val: 10
Val: 14
Val: 15
Val: 16
Val: 17
Val: 18
Val: 19
Val: 20
Val: 135229

I am just not sure how to sort this list without passing GetNode a zero, my professor, wants us to do it a differen't way.

Here is my code (to run program type: ./a.out infile outfile:

CODE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

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

struct NumNodeType
{
    int dat;
    struct NumNodeType *next;
};

/* Define new type names:  BaseElem   and   BasePtr  
* to refer to the list nodes.  These new names can
* be used in place of struct NumNodeType and
* struct NumNodeType *  repsectively.
*/
typedef struct NumNodeType BaseElem;
typedef struct NumNodeType * BasePtr;

/* --------------------------------------------------------------------- */
int str_to_int(char s[])
{
  
   int i=0,j,d,num=0;
   char c;

   while (s[i] != '\0')
   {
      c = s[i];
      
      if ( c >= '0' && c <= '9')
       d = c - '0';
      if ( c >= 'A' && c <= 'K')
       d = (c - 'A') + 10;
        
      
      //printf("\nDigit %d\n", d);
      num = num * 21 + d;
      i++;
   }

   return num;
}


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

BasePtr GetNode( int val )
{
    BasePtr node;
    node = malloc( sizeof(BaseElem) );
    node->dat = val;
    node->next = NULL;
    return node;    
}


int Length( BasePtr first )
{
    BasePtr move;
    int len=0;
    move = first;
    while (move != NULL)
    {
        len++;
        move = move->next;
    }
    return len;
}


void PrintNode( FILE *ofp, BasePtr node )
{
    fprintf(ofp, "Val: %d\n", node->dat);
    printf("Val: %d\n", node->dat);
}

void PrintList( FILE *ofp, BasePtr first )
{
    BasePtr move;
    move = first;
    while (move != NULL)
    {
        PrintNode( ofp, move);
        move = move->next;
    }
}

void PrintNodeFile( FILE *ofp, BasePtr node )
{
    fprintf(ofp, "Val: %d\n", node->dat);
}

void PrintListFile( FILE *ofp, BasePtr first )
{
    BasePtr move;
    move = first;
    while (move != NULL)
    {
        PrintNodeFile( ofp,  move );
        move = move->next;
    }
}

int Compare( int x, int y)
{
    if (x < y) return -1;
    else if (x == y) return 0;
    else if (x > y) return 1;
}

BasePtr FindInsLoc( BasePtr first, BasePtr node )
{
    BasePtr move, prev;
    int val1, val2;
    int res = -1;
    val2 = node->dat;
    move = first;
    prev = move;

    val1 = move->dat;
    res = Compare( val1, val2 );

    while ( res < 0 && move != NULL)
    {
        prev = move;
        move = move->next;
        if (move != NULL)
        {
            val1 = move->dat;
            res = Compare( val1, val2 );
        }
    }    
    return prev;
}

BasePtr InsertNodeAfter( BasePtr first, BasePtr loc, BasePtr node)
{
    //printf("Insert %d after %d\n", node->dat, loc->dat);
    node->next = loc->next;
    loc->next = node;
    return first;
}


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

int main( int argc, char *argv[] )
{
    BasePtr head, tail, tmp;
    int i;

    FILE *infile, *outfile;
    /* verify that 2 parameters were passed */    
    if ( argc != 3)
    {
        printf("Usage: a.out infile outfile\n");
        return 1;
    }
    /* open input file */
    infile = fopen( argv[1], "r");
    if (!infile)
    {
        printf("ERROR: file %s not available\n", argv[1]);
        return 1;    
    }
    /* open output file */
    outfile = fopen( argv[2], "w");
    if (!outfile)
    {
        printf("ERROR: file %s not available\n", argv[2]);
        return 1;    
    }
    
    int z;
    fscanf(infile, "%d", &z);
  
    char str2[5];
    int k;
    fscanf(infile, "%s", str2);
    k = str_to_int(str2);
    tmp = GetNode(k);
    head=tmp;
    tail=tmp;

    
    fprintf(outfile, "List Size: %d\n", z);
    fprintf(outfile, "Sorted List: \n");
    PrintListFile(outfile, head);        
    printf("List size: %d\n", z);

    /*

    /* now make it work some some random data; the above
     * code is a test case in a controlled situation to make
     * sure things appear to work
     */
  /* insertion sort */

    BasePtr start, p, add;
    int x;
    tmp = GetNode(0);
    start=tmp;
    char str[5];
    
    

    for (i = 1; i < z; ++i)
    {
        fscanf(infile, "%s", str);  
        x = str_to_int(str);
        
        printf("Inserting %d\n", x);
        add = GetNode(x);
        p = FindInsLoc( start, add );
        start = InsertNodeAfter( start, p, add );
        
    }

    printf("----- Sorted list ----- \n");
    PrintList( outfile, start );

    return 0;
}


This post has been edited by kkgaming: 9 Apr, 2007 - 11:26 PM
User is offlineProfile CardPM
+Quote Post

NickDMax
RE: Linked List (sorting)
10 Apr, 2007 - 09:22 AM
Post #2

2B||!2B
Group Icon

Joined: 18 Feb, 2007
Posts: 2,858



Thanked: 49 times
Dream Kudos: 550
My Contributions
There are LOTs of sorting algorithms, and I don't think many of them would require you to call getNode(0).

For example a bubble sort would start at first, compair first->val with first->next->val and then swap the two nodes if they needed it. It never has to call getNode(0).

Linked lists work well with an insertion sort (point in fact linked lists often use the idea of an insertion sort to insert new nodes so that the list is always sorted).

There is also a merge sort, and a quick sort (both are a little more complicated by the list structure, but they can be implimented). The merg sort is a favorite for working with linked lists. NOtes on merge sort in linked lists

If you are new to sorting try the bubble sort first, then I would work on understanding the insertion sort, then look up the merge sort. If you feel comfortable with codeing start with the merge sort.
User is offlineProfile CardPM
+Quote Post

kkgaming
RE: Linked List (sorting)
10 Apr, 2007 - 06:13 PM
Post #3

D.I.C Head
**

Joined: 7 Feb, 2007
Posts: 75


My Contributions
QUOTE(NickDMax @ 10 Apr, 2007 - 10:22 AM) *

There are LOTs of sorting algorithms, and I don't think many of them would require you to call getNode(0).

For example a bubble sort would start at first, compair first->val with first->next->val and then swap the two nodes if they needed it. It never has to call getNode(0).

Linked lists work well with an insertion sort (point in fact linked lists often use the idea of an insertion sort to insert new nodes so that the list is always sorted).

There is also a merge sort, and a quick sort (both are a little more complicated by the list structure, but they can be implimented). The merg sort is a favorite for working with linked lists. NOtes on merge sort in linked lists

If you are new to sorting try the bubble sort first, then I would work on understanding the insertion sort, then look up the merge sort. If you feel comfortable with codeing start with the merge sort.



Alright, thanks for the reply, I guess I didn't quite get done, but I got it to sort somewhat.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 09:41PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month