Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chuyển mảng thành danh sách liên kết đôi vòng (Circular Doubly Linked List) trong C++


Cho mảng, chuyển thành danh sách liên kết đôi vòng (circular doubly linked list).

Chương trình minh họa

#include <iostream>
using namespace std;
struct node{
    int data;
    struct node *next, *prev;
};
node* getNode(){ return (node*)malloc(sizeof(node)); }
int print_list(node *temp){
    node *t = temp;
    if(!temp) return 0;
    cout << "List: ";
    while(temp->next != t){
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << temp->data;
    return 1;
}
void convert_array(int arr[], int n, node** start){
    node *newNode, *temp;
    for(int 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;
            (*start)->prev = newNode;
        }
    }
}
int main(){
    int arr[] = {1,2,3,4,5};
    int n = sizeof(arr)/sizeof(arr[0]);
    node *start = NULL;
    convert_array(arr, n, &start);
    print_list(start);
    return 0;
}

Kết quả

List: 1 2 3 4 5