输入共有三行,第一行为该单向循环链表的长度 n(1≤n≤60);第二行为该单向循环链表的各个元素 ,它们各不相同且都为数字;第三行为一个数字 m,表示链表中的一个元素值,要求输出时以该元素为起点反向输出整个双向链表。
输出格式
输出为一行,即完成双向链表后以反向顺序输出该链表,每两个整数之间一个空格,最后一个整数后面没有空格
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *prior;
struct Node *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 output(LinkedList head, int val, int num){
Node *current_node = head;
int count = num;
while(current_node->data != val){
current_node = current_node->next;
}
while(count--){
printf("%d",current_node->data);
current_node = current_node->prior;
if(count != 0){
printf(" ");
}
}
}
int main(){
int n;
scanf("%d\n",&n);
LinkedList *linkedlist = NULL;
for(int i = 0; i < n; i++){
Node *node =(Node *)malloc(sizeof(Node));
scanf("%d ",&node->data);
node->next = NULL;
node->prior = NULL;
linkedlist = insert(linkedlist, node, i);
}
int m;
scanf("%d\n",&m);
output(linkedlist, m, n);
return 0;
}
网友评论