实验7-1-3 将数组中的数逆序存放
Posted 2018jason
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实验7-1-3 将数组中的数逆序存放相关的知识,希望对你有一定的参考价值。
用链表的方法解决
#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("
");
}
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 将数组中的数逆序存放的主要内容,如果未能解决你的问题,请参考以下文章