2011-11-16 62 views
0

我已經使用strtok來標記我的輸入文件,我需要根據我在follwing格式得到了輸出鏈接列表。字符使用C和創建鏈表

String:value-Next --> String:value-Next 

我將字符串和值標記爲我的文件後。

這裏是我的代碼:

FILE *pfi; 
main(int argc, char* argv[]) 
{ 
    char string[1000], delim[] = " \n"; 
char *p; 
    if(argc<2) 
     { 
      printf("entering format is wrong. compile program using gcc digraph.c and then enter it as ./a.out input.txt"); 
     } 
    else if(argc == 2) 
     { 
     pfi=fopen(argv[1],"r"); 
     } 
    if(!pfi) 
     return 1; 
while(fgets(string, sizeof(string)-1, pfi) != NULL) 
    { 
      p = string; 
     p = strtok(string, delim);  

     while(p != NULL) 
      { 

       if (sscanf(p, "(%s ",p)) printf("(\n"); 
      printf("%s\n", p);      

      p = strtok(NULL, delim);     
       } 

     } fclose(pfi); 


return 0; 
} 

的輸入文件格式:

A 20 
B 30 
C 40 

輸出是:

A 
20 
B 
30 
C 
40 

請幫我創建格式的鏈接列表String:value-Next --> String:value-Next

回答

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

/* Create a struct to hold our data in the link list */ 
typedef struct node 
{ 
    char value[100]; 
    int ivalue; 
    struct node *next; 
} Node_t; 

void insertInList(Node_t **root, const char *value, int ivalue); 
void printList(const Node_t *root); 

int main(int argc, char *argv[]) 
{ 
    /* head of link list */ 
    Node_t *root=0; 

    /* ignore this it is C++ - but its quicker to write an input method for it */ 
    bool done=false; 
    while(!done) 
    { 
     /* ignore from here */ 
     std::string value; 
     int ivalue=0; 
     std::cout << "Enter value: " << std::flush; 
     std::cin >> value; 
     if(value.size() && value[0]=='q') 
     { 
     done=true; 
     continue; 
     } 
     std::cout << "Enter ivalue: " << std::flush; 
     std::cin >> ivalue; 
     /* to here */ 
     insertInList(&root, value.c_str(), ivalue); 
    } 

    printList(root); 
    /* Dont forget to free all the link list members after */ 

    return 0; 
} 

/* note head of list is passed as a pointer to a pointer so we can modify it */ 
void insertInList(Node_t **root, const char *value, int ivalue) 
{ 
    Node_t *new_node=*root; 
    Node_t *last_node=0; 

    /* find the end of the list to insert to */ 
    while(new_node) 
    { 
     last_node=new_node; 
     new_node=new_node->next; 
    } 

    /* reserve memory for new node */ 
    new_node=(Node_t *)malloc(sizeof(Node_t)); 
    /* copy data over */ 
    strncpy(new_node->value, value, sizeof(new_node->value)-1); 
    new_node->ivalue=ivalue; 
    new_node->next=0; 
    if(last_node) 
    { 
     /* set previous node in list to point to our new node */ 
     last_node->next=new_node; 
    } 
    else 
    { 
     /* corner case for first element in list */ 
     *root=new_node; 
    } 
} 

void printList(const Node_t *root) 
{ 
    const Node_t *node=root; 

    while(node) 
    { 
     printf("%s %d\n", node->value, node->ivalue); 
     node=node->next; 
    } 
}