在本教程中,我们将讨论将数组转换为圆形双向链表的程序。
为此,我们将提供一个数组。我们的任务是获取数组的元素,并将其转换为圆形的双向链表。
#include<iostream> using namespace std; //双链表的节点结构 struct node{ int data; struct node *next; struct node *prev; }; //节点创建 struct node* getNode(){ return ((struct node *)malloc(sizeof(struct node))); } //打印列表 int print_list(struct node *temp){ struct node *t = temp; if(temp == NULL) return 0; else { cout<<"List: "; while(temp->next != t) { cout<<temp->data<<" "; temp = temp->next; } cout<<temp->data; return 1; } } //将数组转换为链表 void convert_array(int arr[], int n, struct node **start) { //声明新的指针 struct node *newNode,*temp; int i; //遍历所有元素 for(i=0;i<n;i++){ newNode = getNode(); newNode->data = arr[i]; if(i==0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { //计算最后一个节点 temp = (*start)->prev; temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } } } int main(){ int arr[] = {1,2,3,4,5}; int n = sizeof(arr) / sizeof(arr[0]); struct node *start = NULL; convert_array(arr, n, &start); print_list(start); return 0; }
List: 1 2 3 4 5