【问题标题】:String input by linked list链表输入的字符串
【发布时间】:2014-08-31 07:41:01
【问题描述】:

有没有办法通过链表获取字符串输入(就像我们对任何整数一样)??

例如:此代码显示运行时错误:

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

我想获取任何输入字符串,例如 -"asdfghj",其中的字符串长度未知?

【问题讨论】:

  • 哪种语言? C++ 还是 C?

标签: c linked-list


【解决方案1】:

假设您有一个 LinkedList-class 作为链接列表的接口,并且它具有函数 addNode() 以正确的方式将 node 添加到列表中。 我还假设您想知道的是如何使输入的string 中的每个char 成为链表中的node,并且您知道如何管理链表。

假设您使用的是 C++11

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

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

【讨论】:

    【解决方案2】:

    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】:

      你可以轻松思考。因为您只需声明一个字符串变量而不是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;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 2019-05-04
        相关资源
        最近更新 更多