实验7-1-3 将数组中的数逆序存放

2021-05-13 09:28

阅读:350

标签:数组   void   ++   逆序   amp   std   ret   add   can   

用链表的方法解决

#include 
#include 

typedef struct node
{
    int index;
    int number;
    struct node *next;
} NODE, *LINK;

void addNode(LINK head, int n)
{
    LINK tail, newNode;

    tail = head;
    for (int i = 0; i index = i;
        scanf("%d", &(newNode->number));
        newNode->next = NULL;
        tail->next = newNode;
        tail = newNode;
    }
}

void myFun(LINK head)
{
    LINK q;
    LINK p = head->next->next;
    
    head->next->next = NULL;     //逆序后的最后一个结点的下一个结点为NULL
    while (p != NULL)
    {
        q = p->next;
        p->next = head->next;
        head->next = p;
        p = q;
    }
}

void clearList(LINK head)
{
    LINK p;

    while (head != NULL)
    {
        p = head->next;
        free(head);
        head = p;
    }    
}

void printList(LINK head)
{
    LINK p = head->next;
    
    while (p != NULL)
    {
        if (p == head->next)
        {
            printf("%d", p->number);
        }
        else
        {
            printf(" %d", p->number);
        }
        p = p->next;
    }
    printf("\n");
}

int main()
{
    int n;
    LINK head;

    head = (LINK)malloc(sizeof(NODE));
    head->next = NULL;

    scanf("%d", &n);
    addNode(head, n);
    myFun(head);
    printList(head);
    
    clearList(head);

    return 0;
}

实验7-1-3 将数组中的数逆序存放

标签:数组   void   ++   逆序   amp   std   ret   add   can   

原文地址:https://www.cnblogs.com/2018jason/p/13131027.html


评论


亲,登录后才可以留言!