1. 程式人生 > 其它 >【C語言】【鏈串】【初學者】使用鏈式儲存儲存字串

【C語言】【鏈串】【初學者】使用鏈式儲存儲存字串

技術標籤:C初學者c語言字串連結串列

本專案使用鏈式儲存的方式儲存字串;

初學者作品,歡迎各位大佬斧正;


執行效果


全部程式碼

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

struct str{
    char ch;
    struct str *next;
};
struct str *input(struct str *head,char x);
void output(struct str *head);
int main(void){
    char c;
    struct str *head = NULL;
    printf("請輸入一個字串:\n");
    do{
        scanf("%c",&c);
        if(c == '\n'){
            break;
        }else{
            head = input(head,c);
        }
    }while(1);
    output(head);
    free(head);
    return 0;
}
struct str *input(struct str *head,char x){
    struct str *p = NULL,*pr = head;
    p = (struct str *)calloc(1,sizeof(struct str));
    if(head == NULL){
        head = p;
    }else{
        while(pr -> next != NULL){
            pr = pr -> next;
        }
        pr -> next = p;
    }
    p -> ch = x;
    return head;
}
void output(struct str *head){
    struct str *pr;
    pr = head;
    while(pr != NULL){
        printf("%c",pr -> ch);
        pr = pr -> next;
    }
    printf("\n");
}