2014-08-31 27 views
-4

是否有任何方式通過鏈接列表獲取字符串輸入(就像我們對任何整數)?通過鏈接列表輸入字符串

例如:這個代碼表示運行時間錯誤:

struct node 
{ 
    char c; 
    struct node *link; 
}; 
while(1) 
{ 
    val=getch(); 
    if(val!=10) 
     add(&a[i],val); 
    else 
     break; 
} 

和我想利用任何輸入字符串等 - "asdfghj",其字符串長度的不是公知的?

+2

哪種語言? C++還是C? – 2014-08-31 07:50:35

回答

0

例如對於C

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

typedef struct node { 
    char c; 
    struct node *link; 
} Node; 

typedef struct s_ { 
    Node *top; 
    Node *curr; 
} String; 

Node *Node_new(char ch){ 
    Node *p = calloc(1, sizeof *p); 
    p->c = ch; 
    return p; 
} 

String *String_new(void){ 
    String *p = calloc(1, sizeof *p); 
    return p; 
} 

void String_drop(String *s){ 
    Node *p = s->top; 
    while(p){ 
     s->curr = p; 
     p = p->link; 
     free(s->curr); 
    } 
    //s->top = s->curr = NULL; 
    free(s); 
} 

void String_add(String *s, char c){ 
    if(s->top == NULL){ 
     s->curr = s->top = Node_new(c); 
    } else { 
     s->curr = s->curr->link = Node_new(c); 
    } 
} 

String *get_string(FILE *fp){ 
    String *s = String_new(); 
    int ch; 
    while(EOF!=(ch=fgetc(fp)) && ch !='\n'){ 
     String_add(s, (char)ch); 
    } 
    return s; 
} 

void put_string(String *s){ 
    Node *p; 
    for(p = s->top; p ; p = p->link) 
     putchar(p->c); 
    putchar('\n'); 
} 

int main(void) { 
    String *s = get_string(stdin); 
    put_string(s); 
    String_drop(s); 
    return 0; 
} 
3

鑑於您有一個LinkedList類,該類用作鏈接列表的接口,並且它具有函數addNode(),該函數以正確的方式將node添加到列表中。 我還假設你想知道的是如何使鏈接列表中輸入的string a node中的每個char都知道如何管理鏈表。

你正在使用C++ 11

int main() 
{ 
    LinkedList list; 
    string input; 
    cin >> input; 

    for(auto i: input) 
    { 
     list.addNode(i); 
    } 
} 
0

你很容易想到假設。正如你可以聲明一個字符串變量而不是char。之後,您可以通過創建一個結構變量來正常輸入。例如:

#include <bits/stdc++.h> 

using namespace std; 

struct node 
{ 
    string s; 
    struct node *link; 
}; 


int main(){ 

    node ob; 

    cin>>ob.s; 
    cout<<ob.s; 

}