当前位置: 首页 > 编程笔记 >

在C ++中将单链表转换为循环链表

李光华
2023-03-14
本文向大家介绍在C ++中将单链表转换为循环链表,包括了在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
 类似资料:
  • 本文向大家介绍在C ++中将单链表转换为XOR链表,包括了在C ++中将单链表转换为XOR链表的使用技巧和注意事项,需要的朋友参考一下 在本教程中,我们将讨论将单链表转换为XOR链表的程序。 为此,我们将提供一个单链表。我们的任务是获取该列表的元素,并将其转换为XOR链接列表。 示例 输出结果

  • 如何检测单个链表是否有循环??如果有循环,则如何找到循环的起始点,即循环开始的节点。

  • 给定一个单链表和中间节点从一开始的编号,我试图通过将最后一个节点指向中间节点来创建一个循环单链表。我写了以下代码: 然而,Linkedlist的最后一个节点仍然指向null而不是中间节点。我明白我哪里出错了,我找不到它。请帮忙。

  • 我如何转换使用以下代码,我的二叉树到一个简单的链表。这也许可以用递归来完成。 因此,如果根为NULL,也就是,如果函数没有收到有效的指针,则返回错误消息。 如果根是叶,这是,如果左子节点和右子节点都为NULL,您必须将其添加到叶节点列表中。

  • 我创建了一个双循环链表。 我需要知道每个节点到头部的距离。 因为当我必须删除或获取具有特定密钥的节点时,如果两个节点具有相同的密钥和相同的距离,则必须删除或获取这两个节点,否则必须删除最靠近头部的节点。 我不知道如何计算距离,因为它是圆形的。。。 这个链表的插入就是这样工作的。 所有的节点都去追头。 例: 1)头部 2) 头部A(插入A) 3) 头部B-A(插入B) 4) 头部C-B-A(插入C)

  • 我正在用我的java书复习数据结构,我需要重新创建一个循环链表。我对这个无限循环的链表有问题,弄不清楚为什么。我可以将值插入到列表中,但是打印和删除这些值似乎会无限循环最初插入的值。我如何更改我的List类以避免无限循环? CircularList.Class 链接类