zl程序教程

您现在的位置是:首页 >  前端

当前栏目

双向循环链表

循环链表 双向
2023-09-27 14:26:25 时间

输入共有三行,第一行为该单向循环链表的长度 n(1≤n≤60);第二行为该单向循环链表的各个元素 ,它们各不相同且都为数字;第三行为一个数字 m,表示链表中的一个元素值,要求输出时以该元素为起点反向输出整个双向链表。

输出格式
输出为一行,即完成双向链表后以反向顺序输出该链表,每两个整数之间一个空格,最后一个整数后面没有空格。
在这里插入图片描述

#include <stdio.h>
typedef struct Node{
    int data;
    struct Node *prior, *next;
}Node, *LinkedList;

LinkedList insert(LinkedList head, Node *node, int index) {
    if (head == NULL) {
        if (index != 0) {
            return head;
        }
        head = node;
        head->prior = head;
        head->next = head;
        return head;
    }
    if (index == 0) {
        node->next = head;
        node->prior = head->prior;
        head->prior->next = node;
        head->prior = node;
        head = node;
        return head;
    }
    Node *current_node = head;
    int count = 0;
    while (current_node->next != head && count < index - 1) {
        current_node = current_node->next;
        count++;
    }
    if (count == index - 1) {
        node->next = current_node->next;
        node->prior = current_node;
        current_node->next->prior = node;
        current_node->next = node;
     }
    
    return head;
}

void out_put(LinkedList head, int n,int element) {
    Node *current_node = head;
   
    while (current_node->data != element) {
        current_node = current_node->prior;
    }
    
     while (n--) {
        if (current_node->data != element) printf(" ");
        printf("%d",current_node->data);
        current_node = current_node->prior;
    }
    
}

void main() {
    int n,m;
    scanf("%d", &n);
    LinkedList *linkedlist = NULL;
    for (int i = 0; i < n; i++) {
        Node *node = (LinkedList *)malloc(sizeof(LinkedList));
        node->next = NULL;
        node->prior = NULL;
        scanf("%d", &node->data);
        linkedlist = insert(linkedlist,node, i);
    }
    scanf("%d", &m);
    out_put(linkedlist,n, m);
    return 0;
}