c链表

学习了数据结构后,自己学习写了一个链表的程序。
初步功能是实现了。但是不知道会不会有一些隐含的问题。所以希望大佬指导指导
/******************/
/*一个小的链表程序*/
/******************/
#include <stdio.h>
#include <stdlib.h>
//结点的结构体
typedef struct node
{
    char data;
    struct node*next;
}Node;
//链表的结构体
typedef struct
{
    Node *head;
    Node *list1;
    int num;
}NList;
//生成一个链表
void CreateList(NList *list)
{
    list->head = NULL;
    list->list1 = NULL;
    list->num = 0;
}
//向链表中添加数据
void AddList(NList *list)
{
    char data;
    scanf("%c",&data);
    while(data != '#')
    {
        if(list->head == NULL)
        {
            list->head = (Node *)malloc(sizeof(Node));
            list->head->data = data;
            list->head->next = NULL;
            list->list1 = list->head;
            list->num = 1;
        }
        else
        {
            Node *p = (Node *)malloc(sizeof(Node));
            list->list1->next = p;
            p->data = data;
            list->list1 = p;
            list->list1->next = NULL;
            list->num++;
        }
        scanf("%c",&data);
    }
}
//显示链表中的数据
void ShowList(NList list)
{
    Node *P1;
    P1=list.head;
    while(P1 != NULL)
    {
        printf("%c",P1->data);
        P1 = P1->next;
    }
}
//删除链表头的数据
void DelList_head(NList *list)
{
    if(list->head != NULL)
    {
        Node *p2 = list->head;
        list->head = p2->next;
        list->num--;
        free(p2);
    }
    else
    {
        printf("链表中不存在数据\n");
    }
}
int main()
{
    NList list2;
    CreateList(&list2);
    AddList(&list2);
    ShowList(list2);
    printf("\n链表中的数据个数是:%d个\n",list2.num);
    DelList_head(&list2);
    ShowList(list2);
    printf("\n链表中的数据个数是:%d个\n",list2.num);
    return 0;
}

程序的执行结果如下:

猜你喜欢

转载自www.cnblogs.com/ghost-98210/p/9544789.html