#include <stdio.h>
#include <stdlib.h>
/*链表结构体*/
typedef struct List{
int data;
struct List *next;
}List;
/*创建链表 插入数据*/
List * creatList(List *head,int data)
{
if(head == NULL)
{
/*创建头结点*/
head = (List*)malloc(sizeof(List));
head->next = NULL;
}
else /*插入数据*/
{
List *Node = (List*)malloc(sizeof(List));
/*让新来的节点有所指向*/
Node->next = head->next;
Node->data = data;
/*进行插入操作*/
head->next = Node;
}
return head;
}
/*遍历链表*/
void travel1_List(List *head)
{
/*出去空头节点*/
head = head->next;
while(head)
{
printf("%d ",head->data);
head = head->next;
}
}
/*对遍历链表进行改写 用来给数组赋值*/
int travel_List(List *head,int str[])
{
int i=0;
head = head->next;
while(head)
{
str[i++] = head->data;
head = head->next;
}
return i;
}
int main(void)
{
List * head = NULL;
int str[10]={0};
int i;
int num;
srand(time(NULL));
for(i=0;i<=10;i++)
{
head = creatList(head,rand()%15);
}
travel1_List(head);
num = travel_List(head,str);
printf("num = %d\n",num);
for(i=num-1;i>=0;i--)
{
printf("%d ",str[i]);
}
return 0;
}
链表的逆序输出 (C语言)
最新推荐文章于 2022-03-26 16:28:01 发布