码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-06-15 16:15:24      阅读:80      评论:0      收藏:0      [点我收藏+]

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

用链表的方法解决

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

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 < n; i++)
    {
        newNode = (LINK)malloc(sizeof(NODE));
        newNode->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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!