2017-02-26 131 views
0

我正在创建用户输入的字符串的链接列表。截至目前,我有我的链接列表工作(我只需要释放内存)。但是,我试图在用户输入中检测逗号。如果有逗号,则链接列表会打印出一个新行,并忽略逗号。搜索LinkedList中的元素

有什么建议吗?

例如:

输入一个字符串:

你好,世界,怎么样,是,你

输出是目前:

你好,世界怎么,是,你

输出sh乌尔德是:

你好

世界

如何

这里是我当前的代码:

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

struct Word 
{ 
    char* data; 
    struct Word* next; 
}; 

struct Word* ptr = NULL; 


void insert(char c) 
{ 
    struct Word* temp = (struct Word*)malloc(sizeof(struct Word)); 

    temp->data = c; 
    temp->next = NULL; 

    if (ptr) { 
     struct Word* temp1 = ptr; 

     while(temp1->next != NULL) { 
      temp1 = temp1->next; 
     } 

     temp1->next = temp; 

    } else { 
     ptr = temp; 
    } 

} 

void print() { 

    struct Word *temp; 
    temp = ptr; 

    while(temp != NULL) { 

     printf("%c", temp->data); 
     temp = temp->next; 

    } 

    printf("\n"); 

} 

int main(int argc, char *argv[]) 
{ 
    int c; 

    printf("enter a string\n"); 
    while (((c=getchar())!=EOF) && c!='\n') { 
     insert((char)c); 
    } 

    print(); /*print the list*/ 
    return 0; 
} 
+0

你为什么要使用pointer-to-char来存储一个简单的char!这个答案也很明显是错误的,因为它没有指示做正确的事情:'char * data'应该是'char data',现在代码中充满了未定义的行为 - 您应该编译时启用所有警告! –

回答

0

要打印新行中的每个单词,只需修改打印语句以检查链接列表中的,字符。

void print() { 

struct Word *temp; 
temp = ptr; 
char c; 

while(temp != NULL) { 

    if (temp->data == ',') { 
     printf("\n"); 
     temp = temp->next; 
    } else { 
     printf("%c", temp->data); 
     temp = temp->next; 
    } 

} 

    printf("\n"); 

} 

这将检查是否有在链表,和打印\n打印换行符,并移动到下一个节点。

此外,您应该在程序完成后释放链接列表以避免内存泄漏。

void freeData(struct Word* head) 
{ 
    struct Word* tmp; 

    while (head != NULL) 
    { 
     tmp = head; 
     head = head->next; 
     free(tmp); 
    } 

} 

Code link

只是尝试一下。

+0

当你认为这不是那么简单....恩,非常感谢!编译时声明一条警告消息:比较temp-> data ==','....上的新if语句的指针和整数。 – Karth

+0

@Ayush wat,不! –

+0

@Karth修复错误,您必须将'data'声明为'char',而不是'char *'。这也是由于其他因素造成的,所以您不需要指针来存储单个字符,也不会为指针char * data存储alloc()内存。 – linuxfan