单链表插入与倒叙

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hua12134/article/details/79156550

题目:单链表的建立,把’a’ —’z’ 26个字母插入到链表中,并且倒叙,还要打印。

此题解法很多,本篇采用不带头结点的单链表头插法插入,然后正序打印。

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

#define  OK      1;
#define  ERROR  -1;

typedef char ElemType;

typedef struct node
{
    ElemType data;
    struct node* next;
}Node;

int InsertHead(Node** h, char data)
{
    Node* node = (Node*)malloc(sizeof(Node) / sizeof(char));
    if (NULL == node)
    {
        return ERROR;
    }

    node->data = data;
    node->next = *h;
    *h = node;

    return OK;
}

int main()
{
    Node *head = NULL;

    for (char c = 'a'; c <= 'z'; c++)
    {
        InsertHead(&head, c);
    }

    Node* tmp = head;
    while(tmp)
    {
        printf("%c ", tmp->data);
        tmp = tmp->next;
    }
    printf("\n");

    return 0;
}

猜你喜欢

转载自blog.csdn.net/hua12134/article/details/79156550
今日推荐