Left justification using linked list of link list

This is a discussion on Left justification using linked list of link list within the C Programming forums, part of the General Programming Boards category; Hey there~ I need to write a program to left justify text stored in the link list. Here's part of ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    15

    Left justification using linked list of link list

    Hey there~ I need to write a program to left justify text stored in the link list. Here's part of my program:-

    Structure:-
    Code:
    typedef struct charStruct
    {
       char alphabet;
       struct charStruct* nextChar;
    } CharacterNode;
    
    typedef struct lineHeaderStruct
    {
       CharacterNode* firstChar;
       struct lineHeaderStruct* nextLine;
    } LineHeaderNode;
    
    typedef struct mainHeaderStruct
    {
       int fileSize;
       LineHeaderNode* firstLine;
    } FileADT;
    Function:-
    Code:
    #define LINESIZE 69;
    
    void FileFormat(FileADT *fileNode)
    {
      LineHeaderNode *newLineNode, *currentLineNode, *nextLineNode;
      CharacterNode *newCharNode, *currentCharNode,  *previousCharNode;
      int lineLength = 1;
    
      currentLineNode = fileNode->firstLine;
      currentCharNode = fileNode->firstLine->firstChar;
    
      while(currentCharNode != NULL)
      {
          if(lineLength > LINESIZE)
          {
            newCharNode = createNewCharNode('\n');
            newLineNode = createNewLineNode();
    
            currentLineNode->nextLine = newLineNode;
            newLineNode->nextLine = nextLineNode;
    
            previousCharNode->nextChar = newCharNode;
    
            newLineNode->firstChar = currentCharNode;
    
            currentLineNode = newLineNode;
            nextLineNode = currentLineNode->nextLine;
            
            lineLength = 0;
          }
    
          else
          {
            if(currentCharNode->alphabet == '\n')
            {
              currentLineNode = currentLineNode->nextLine;
              nextLineNode = currentLineNode->nextLine;
              currentCharNode = currentLineNode->firstChar;
    
              lineLength = 0;
            }
            else
            {
              previousCharNode = currentCharNode;
              currentCharNode = currentCharNode->nextChar;
            }
          }
    
          lineLength++;
      }
    }
    
    CharacterNode* createNewCharNode(char character)
    {
      CharacterNode *newCharNode;
    
      newCharNode->alphabet = character;
      
      return newCharNode;
    }
    
    LineHeaderNode* createNewLineNode()
    {
      LineHeaderNode *newLineNode;
    
      return newLineNode;
    }
    The output will be weird because it breaks words into parts and store them in the next line but its ok because i want to get this part to work before going any further..So actually this function is incomplete..And i removed the malloc() function from the program to make it shorter and less irritating..I think i'll show you the example of my output..

    Original text
    Code:
    Today, computer software is the single most important technology on the world stage.
    And it is also a prime example of the law of unintended consequences.
    Intended output
    Code:
    Today, computer software is the single most im
    portant technology on the world stage.
    And it is also a prime example of the law of un
    intended consequences.
    Output Received
    Code:
    Today, computer software is the single most im
    portant technology on the world stage.
    /*This line is missing*/
    Hope you'll be able to help me out here..I'll post my other two functions (adding to link list and display) if you think i should..I've been sitting here for more than 5 hours today and still not able to find whats wrong with it..My butt really hurts ..Help will be greatly appreciated!! Thanks a lot for taking time to read this!!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,338
    > #define LINESIZE 69;
    This code doesn't compile - I've already had a go at someone else this week for posting what they didn't compile.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    Hmm...I dont really get it...Sorry bout that~ Does that mean i should post the source code for my whole program? Then i think i'll post it~ And i think i'll also provide a link so that you can DL the whole program..
    FileADT

    Small explaination:
    What this program does is read in text file through command line arguement and store each character in a character node. After every "\n" or new line, it moves on to the next line node and store characters again and the whole process is repeated again..After that it will left justify the text and display the output...

    fileadt.h
    Code:
    /* Header files. */
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct charStruct
    {
       char alphabet;
       struct charStruct* nextChar;
    } CharacterNode;
    
    typedef struct lineHeaderStruct
    {
       CharacterNode* firstChar;
       struct lineHeaderStruct* nextLine;
    } LineHeaderNode;
    
    typedef struct mainHeaderStruct
    {
       int fileSize;
       LineHeaderNode* firstLine;
    } FileADT;
    
    /* Function prototypes. */
    int FileOpen(FileADT *, char *);
    void FileFormat(FileADT *);
    void FileDisplay(FileADT *);
    fileadt.c
    Code:
    /* Header Files */
    #include "fileadt.h"
    #include <stdio.h>
    #include <stdlib.h>
    
    /* Function Prototypes */
    void checkArguments(int);
    
    /* Main Program which takes in arguments from Unix*/
    int main(int argc, char *argv[])
    {
      FileADT fileNode;
      int status;
    
      checkArguments(argc);
    
      status = FileOpen(&fileNode, argv[1]);
    
      if(status <= 0)
      {
        return EXIT_FAILURE;
      }
    
      FileFormat(&fileNode);
    
      FileDisplay(&fileNode);
    
      return EXIT_SUCCESS;
    }
    options.c
    Code:
    /* Header Files */
    #include "fileadt.h"
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    /* Define Constants */
    #define LINESIZE 69
    
    /* Function prototypes */
    int checkFileExists();
    CharacterNode* createNewCharNode(char);
    LineHeaderNode* createNewLineNode();
    
    int FileOpen(FileADT *fileNode, char *filename)
    {
      FILE *input;
      LineHeaderNode *newLineNode, *currentLineNode;
      CharacterNode *newCharNode, *currentCharNode;
      int success, character;
      int totalChar = 0;
    
      newLineNode = malloc(sizeof(LineHeaderNode));
      newCharNode = malloc(sizeof(CharacterNode));
      currentLineNode = malloc(sizeof(LineHeaderNode));
      currentCharNode = malloc(sizeof(CharacterNode));
    
      if(newLineNode == NULL || newCharNode == NULL || currentLineNode == NULL || currentCharNode == NULL)
      {
        printf("Not enough memory to create new node!!");
        printf("\nTerminating...\n");
        exit(-1);
      }
    
      /* Opening file for reading */
      input = fopen(filename, "r");
    
      success = checkFileExists(input);
    
      if(success >= 0)
      {
        /* Initialising ADT */
        fileNode->firstLine = NULL;
        fileNode->fileSize = 0;
    
        currentLineNode = fileNode->firstLine;
    
        /* Gets character from input file */
        while((character = fgetc(input)) != EOF)
        {
          /*If firstLine of node is already created */
          if(currentLineNode != NULL)
          {
            currentCharNode = currentLineNode->firstChar;
    
            newCharNode = createNewCharNode(character);
    
            /* If there are no characters yet in the lineNode */
            if(currentCharNode == NULL)
            {
              currentLineNode->firstChar = newCharNode;
            }
    
            /* If there are already characters in the lineNode */
            else
            {
              /*Traverse character node until the last character */
              while(currentCharNode->nextChar != NULL)
              {
                currentCharNode = currentCharNode->nextChar;
              }
    
              currentCharNode->nextChar = newCharNode;
            }
          }
    
          /* If firstLine of node is not yet created */
          else
          {
            newLineNode = createNewLineNode();
            fileNode->firstLine = newLineNode;
            
            newCharNode = createNewCharNode(character);
            newLineNode->firstChar = newCharNode;
    
            currentLineNode = newLineNode;
          }
    
          /* If character is ENTER then create a newLineNode and move to the newly created line node */
          if(character == '\n')
          {
            newLineNode = createNewLineNode();
    
            currentLineNode->nextLine = newLineNode;
            currentLineNode = newLineNode;
          }
    
          totalChar++;
        } 
      
        /* Close file */
        fclose(input);
    
        return 1;
      }
    
      else
      {
        return -1;
      }
    }
    
    void FileDisplay(FileADT *fileNode)
    {
      LineHeaderNode *currentLineNode;
      CharacterNode *currentCharNode;
    
      currentLineNode = malloc(sizeof(LineHeaderNode));
      currentCharNode = malloc(sizeof(CharacterNode));
    
      if(currentLineNode == NULL || currentCharNode == NULL)
      {
        printf("Not enough memory to create new node!!");
        printf("\nTerminating...\n");
        exit(-1);
      }
    
      currentLineNode = fileNode->firstLine;
      currentCharNode = fileNode->firstLine->firstChar;
    
      while(currentCharNode != NULL)
      {
          printf("%c", currentCharNode->alphabet);
    
          if(currentCharNode->alphabet == '\n')
          {
            currentLineNode = currentLineNode->nextLine;
            currentCharNode = currentLineNode->firstChar;
          }
    
          else
          {
            currentCharNode = currentCharNode->nextChar;
          }
      }
    }
    
    void FileFormat(FileADT *fileNode)
    {
      LineHeaderNode *newLineNode, *currentLineNode, *nextLineNode;
      CharacterNode *newCharNode, *currentCharNode, *previousCharNode;
      int lineLength = 1;
    
      newLineNode = malloc(sizeof(LineHeaderNode));
      newCharNode = malloc(sizeof(CharacterNode));
      currentLineNode = malloc(sizeof(LineHeaderNode));
      currentCharNode = malloc(sizeof(CharacterNode));
      nextLineNode = malloc(sizeof(LineHeaderNode));
      previousCharNode = malloc(sizeof(CharacterNode));
    
      if(newLineNode == NULL || newCharNode == NULL || currentLineNode == NULL || 
         currentCharNode == NULL || nextLineNode == NULL || previousCharNode == NULL)
      {
        printf("Not enough memory to create new node!!");
        printf("\nTerminating...\n");
        exit(-1);
      }
    
      currentLineNode = fileNode->firstLine;
      currentCharNode = fileNode->firstLine->firstChar;
    
      while(currentCharNode != NULL)
      {
          if(lineLength > LINESIZE)
          { 
            newCharNode = createNewCharNode('\n');
            newLineNode = createNewLineNode();
    
            currentLineNode->nextLine = newLineNode;
            newLineNode->nextLine = nextLineNode;
    
            previousCharNode->nextChar = newCharNode;
    
            newLineNode->firstChar = currentCharNode;
    
            currentLineNode = newLineNode;
            nextLineNode = currentLineNode->nextLine;
            
            lineLength = 0;
          }
    
          else
          {
            if(currentCharNode->alphabet == '\n')
            {
              currentLineNode = currentLineNode->nextLine;
              nextLineNode = currentLineNode->nextLine;
              currentCharNode = currentLineNode->firstChar;
    
              lineLength = 0;
            }
            else
            {
              previousCharNode = currentCharNode;
              currentCharNode = currentCharNode->nextChar;
            }
          }
    
          lineLength++;
      }
    }
    utility.c
    Code:
    /* Header Files */
    #include "fileadt.h"
    #include <stdlib.h>
    #include <stdio.h>
    
    /* Function prototypes */
    void checkArguments(int);
    int checkFileExists();
    CharacterNode* createNewCharNode(char);
    LineHeaderNode* createNewLineNode();
    
    /* Checks if total arguments are correct */
    void checkArguments(int argc)
    {
      if (argc != 3)
      {
        fprintf(stderr,"Usage: fileadt <inputfile> <outputfile>\n");
        exit(EXIT_FAILURE);
      }
    }
    
    /* Checks if external file exists */
    int checkFileExists(FILE *file)
    {
      if(file == NULL)
      {
        fprintf(stderr,"Failed to open input file!! \n");
        fprintf(stderr,"Exiting program....\n");
        return -1;   
      }
    
      else
      {
        printf("Input file opened successfully!!\n");
        return 1;
      }
    }
    
    CharacterNode* createNewCharNode(char character)
    {
      CharacterNode *newCharNode;
    
      newCharNode = malloc(sizeof(CharacterNode));
    
      if(newCharNode == NULL)
      {
        printf("Not enough memory to create new node!!");
        printf("\nTerminating...\n");
        exit(-1);
      }
    
      newCharNode->alphabet = character;
      
      return newCharNode;
    }
    
    LineHeaderNode* createNewLineNode()
    {
      LineHeaderNode *newLineNode;
    
      newLineNode = malloc(sizeof(LineHeaderNode));
    
      if(newLineNode == NULL)
      {
        printf("Not enough memory to create new node!!");
        printf("\nTerminating...\n");
        exit(-1);
      }
    
      return newLineNode;
    }
    And here's the text file, the first one works but the second one doesnt..
    Code:
    What A Wonderful Weekend
    
    It was Thursday. We were looking forward to Friday and the weekend that follows.
    
    The wind continued to blow from Sumatra and the 
    air pollution index (API) went up and up. In the afternoon, the ministry announced that 
    all schools be closed for the rest of the day as well as Friday. Cancellation of 
    classes has always been the best thing that can ever happen to students and lecturers.
    On this day, 
    the API 
    told us that it was unhealthy to be happy at all.
    
    Friday evening, when i was sitting down for dinner at the poolside, thinking that we 
    were finally outside the house, a horrifying sight hit me, our beautiful pools had 
    turned brownish green!
    
    Needless to say, for the rest of the weekend, we had to stay indoor watching even the
    silliest TV programmes.
    This one doesnt work...
    Code:
    Today, computer software is the single most important technology on the world stage.
    And it is also a prime example of the law of unintended consequences.
    No one in the 1950s could have predicted that software would become an indispensable technology for business, science, and engineering;
    that software would enable the creation of new technologies (e.g., genetic engineering), the extension of existing technologies (e.g., telecommunications),
    and the demise of older technologies (e.g., the printing industry); that software would be the driving force behind the personal computer revolution;
    that shrink-wrapped software products would be purchased by consumers in neighborhood malls;
    that a software company would become larger and more influential than the vast majority of industrial-era companies;
    that a vast software-driven network called the Internet would evolve and change everything from library research to consumer shopping to the dating habits of young (and not-so-young) adults.
    Thanks for not having a go with me (yet??), Salem~ Hope i didnt do anything wrong this time..And hope you all can help me out with this! Thanks again~

  4. #4
    Banned
    Join Date
    Jun 2005
    Posts
    594
    is this some kind of assignment, is a linked list a requirement?
    cause i can think of a lot faster way / with alot less code
    then this.

    sorry wanst paying attention what forum i was in, if this code is
    negoitable in the way you achieve it, meaning you can use
    C or C++, and you dotn have to use a certian technique to
    achieve the goal. the the following C++ code
    may be of use, the LEAST it could do, is give you an idea
    of another way to do it, IF IF, you can do it another way.
    if nto sorry for wasting the time, but here ya go.

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
    	int length = 0;
    	string sfile;
    	ifstream in("file.txt");
    	ofstream out("newfile.txt");
    	if( in.is_open() )
    	{
    		while( in >> sfile )
    		{
    			length += sfile.size() + 1;
    			if( length < 69 )
    			{
    				out << sfile << " ";
    			}
    			else
    			{
    				out << "\n" << sfile << " ";
    				length = sfile.size() + 1;
    			}
    		}
    	}
    	cout << "Completed!" << endl;
    	cin.get();
    	return 0;
    }
    Code:
    Today, computer software is the single most important technology on 
    the world stage. And it is also a prime example of the law of 
    unintended consequences. No one in the 1950s could have predicted 
    that software would become an indispensable technology for 
    business, science, and engineering; that software would enable the 
    creation of new technologies (e.g., genetic engineering), the 
    extension of existing technologies (e.g., telecommunications), and 
    the demise of older technologies (e.g., the printing industry); 
    that software would be the driving force behind the personal 
    computer revolution; that shrink-wrapped software products would be 
    purchased by consumers in neighborhood malls; that a software 
    company would become larger and more influential than the vast 
    majority of industrial-era companies; that a vast software-driven 
    network called the Internet would evolve and change everything from 
    library research to consumer shopping to the dating habits of young 
    (and not-so-young) adults.
    this my output on that previous, i dont know exactly what you
    where trying to acheive, but if you need a newline after the end
    of a sentence, that coudl be easily added.

    if you display a interest on your part ill help you understand the
    code better. and how to easily change it.
    Last edited by ILoveVectors; 08-27-2005 at 12:11 AM.

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,338
    I don't see how your FileFormat() does anything at all. Your interface is via your FileADT, but you only ever read from it inside your format function.

    Sure you create a whole new list-of-lists but you never store it back to your FileADT where FileDisplay can access it.

    Oh, and your code is riddled with memory leaks, but I guess that's a question for later.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    >ILoveVectors
    LOL~ Yeah~ Using link list is a requirement and i have to use linked list of link list too T_T..And you got the output that i wanted too! I just thought i should start slowly first before performing more of the complicated justifying functions..But i appreciate your help and reply a lot!! Thanks!

    > Salem
    Whaat? You mean the original FileADT is not changed when i perform the FileFormat() function??? But i tried displaying all the text before and after the FileFormat() function and it was different..So i thought my link list was changed after the FileFormat() function...Sorry bout this but can you give me an example of how i can store back to my FileADT after FileFormat() ?? A very simple example will be enough.. Im not really good in C programming..I think my fundamentals are not that stong yet too..And I'll work on the memory leakage when im almost finished with the program~ IF i can finish my program that is~

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Here's the problem with
    Code:
    #define LINESIZE 69;
    .

    Say you have this code:
    Code:
    #define LINESIZE 69;
    func(LINESIZE);
    The preprocessor will expand that to
    Code:
    func(69;);
    which doesn't compile. So don't put semicolons after #defines.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    Ooohhhh~ So thats what Salem meant~ Sorry bout that~ Anyways i managed to work things out and im close to completing the whole function~ If i still have any problems i might bring it up again~ Thanks for all the help~!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 05:55 PM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. linked list logic
    By xion in forum C++ Programming
    Replies: 4
    Last Post: 02-09-2005, 02:10 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. Please help me
    By teedee46 in forum C++ Programming
    Replies: 9
    Last Post: 05-06-2002, 11:28 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21