在 C++ 中將單鏈錶轉換為迴圈連結串列
在本教程中,我們將討論一個將單鏈錶轉換為迴圈連結串列的程式。
為此,我們將提供一個單鏈表。我們的任務是獲取該連結串列中的元素,並將其轉換為一個迴圈連結串列。
示例
#include <bits/stdc++.h>
//node structure of linked list
struct Node {
int data;
struct Node* next;
};
//converting singly linked list
//to circular linked list
struct Node* circular(struct Node* head){
struct Node* start = head;
while (head->next != NULL)
head = head->next;
//assigning start to the head->next node
//if head->next points to NULL
head->next = start;
return start;
}
void push(struct Node** head, int data){
//creation of new node
struct Node* newNode = (struct Node*)malloc
(sizeof(struct Node));
//putting data in new node
newNode->data = data;
newNode->next = (*head);
(*head) = newNode;
}
//displaying the elements of circular linked list
void print_list(struct Node* node){
struct Node* start = node;
while (node->next != start) {
printf("%d ", node->data);
node = node->next;
}
printf("%d ", node->data);
}
int main(){
struct Node* head = NULL;
push(&head, 15);
push(&head, 14);
push(&head, 13);
push(&head, 22);
push(&head, 17);
circular(head);
printf("Display list: \n");
print_list(head);
return 0;
}輸出
Display list: 17 22 13 14 15
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP