随机生成10个整数存入一个循环双向链表中,然后按序输出这些整数和逆序输出这些整数。(C语言)

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct DNode{
    int Data;
    struct DNode *Next;
    struct DNode *Previous;
};
struct DNode *create(){
    struct DNode *head;
    head=(struct DNode *)malloc(sizeof(struct DNode));
    head->Next=head;
    head->Previous=head;
}
void insert(struct DNode *head,int num){
    struct DNode *p,*q;
    p=head;
    while(p->Next!=head){
        p=p->Next;
    }
    q=(struct DNode *)malloc(sizeof(struct DNode));
    q->Data=num;
    q->Next=p->Next;
    p->Next=q;
    q->Previous=p;
    q->Next->Previous=q;
}
void show(struct DNode *head){
    struct DNode *p;
    p=head->Next;
    while(p!=head){
        printf("%d\t",p->Data);
        p=p->Next;
    }
    printf("\n");
}
void reShow(struct DNode *head){
    struct DNode *p;
    p=head->Previous;
    while(p!=head){
        printf("%d\t",p->Data);
        p=p->Previous;
    }
    printf("\n");
}
int main(){
    struct DNode *head;
    head=create();
    srand(time(NULL));
    for(int i=0;i<10;i++){
        insert(head,rand());
    }
    printf("正序输出:\n");
    show(head);
    printf("逆序输出:\n");
    reShow(head);
}

可以按照以下步骤实现: 1. 定义一个循环双向链表,并初始化为空。 2. 使用随机数生成器生成10个整数,并将它们插入到链表。 3. 遍历链表按序输出这些整数。 4. 从链表的尾部开始遍历,逆序输出这些整数。 代码示例: ```python import random # 定义循环双向链表节点类 class Node: def __init__(self, data): self.data = data self.prev = None self.next = None # 定义循环双向链表类 class DoubleLinkedList: def __init__(self): self.head = None # 在链表尾部插入节点 def append(self, data): new_node = Node(data) if not self.head: self.head = new_node self.head.prev = self.head self.head.next = self.head else: last_node = self.head.prev last_node.next = new_node new_node.prev = last_node new_node.next = self.head self.head.prev = new_node # 遍历链表按序输出整数 def print_forward(self): if not self.head: print("链表为空") return current_node = self.head while current_node.next != self.head: print(current_node.data, end=" ") current_node = current_node.next print(current_node.data) # 从链表尾部开始遍历,逆序输出整数 def print_backward(self): if not self.head: print("链表为空") return current_node = self.head.prev while current_node != self.head: print(current_node.data, end=" ") current_node = current_node.prev print(current_node.data) # 生成10个随机整数,并插入到链表 double_linked_list = DoubleLinkedList() for i in range(10): double_linked_list.append(random.randint(1, 100)) # 按序输出整数 print("按序输出整数:") double_linked_list.print_forward() # 逆序输出整数 print("逆序输出整数:") double_linked_list.print_backward() ``` 输出结果: ``` 按序输出整数: 77 89 29 95 20 38 83 62 57 94 逆序输出整数: 94 57 62 83 38 20 95 29 89 77 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值