C语言动态链表创建 2021.7.13

主要目的是复习知识点,耗时一个下午。。。

#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef struct LNode//重命名struct LNode为LNode 
{
    int data;
    LNode* next;//在结构体中可以直接使用新名字LNode 
}LNode;

void CreateLinklist(LNode*& head)
{
    printf("请输入数字创建链表,以9999结束。\n");
    head = (LNode*)malloc(sizeof(LNode));
    head->data = NULL;
    head->next = NULL;
    LNode* flag = (LNode*)malloc(sizeof(LNode));
    flag = head;
    int t;
    scanf_s("%d", &t);
    while (t != 9999)
    {
        flag->data = t;
        flag->next = (LNode*)malloc(sizeof(LNode));
        flag = flag->next;
        flag->data = t;
        scanf_s("%d", &t);
    }
    flag->next = NULL;
    flag = head;
}

void printLinklist(LNode* p)
{
    if (p->data == NULL)
        printf("链表为空。\n");
    else
    {
        printf("链表的结构为:\n");
        while (p->next != NULL)
        {
            printf("%d", p->data);
            p = p->next;
            if (p->next != NULL)
                printf(" -> ");
        }
    }
}

/*
void sort(LNode *&headA , LNode *&p)
{
    while
}
*/

int main()
{
    LNode* LA;
    CreateLinklist(LA);
    printf("\n");
    printLinklist(LA);
    return 0;
}

 

posted on 2021-07-13 17:35  学群  阅读(155)  评论(0)    收藏  举报