1.将单链接列表转换为循环链接列表。
2.检查循环链接列表中的节点数
3.检查给定列表是否为循环链接列表。
1.将单链接列表转换为循环链接列表
为此,我们需要遍历列表的末尾并将最后一个节点的下一个分配给列表的开头
2.检查循环链接列表中的节点数
为此,我们取一个临时节点,并开始计算节点数,直到临时节点不等于头节点为止。
3.检查给定列表是否为循环链接列表。
为此,我们需要一个临时节点并开始遍历列表,直到临时节点不等于head为止,或者在非循环LL情况下直到临时节点为空。
C ++解决方案
#include<iostream> #include<vector> #include<string> using namespace std; struct Node { int data; Node *next; Node(int x) { data = x; next = NULL; } }; void print_list(Node *head) { Node *start = head; while(start) { cout<<start->data<<" -> "; start = start->next; } cout<<"\n"; } void make_linked_list_circular(Node *head) { Node *start = head; while(head -> next != NULL) head = head -> next; head -> next = start; } void count_nodes_circular_linked_list(Node *head) { Node *temp = head -> next; int count = 1; while(temp != head) { count++; temp = temp -> next; } cout<<"\n\nThe total number of nodes in circular linked list is "<< count << endl; } void check_if_list_is_circular_linked_list(Node *head) { Node *temp = head -> next; while(temp != NULL && temp != head) temp = temp -> next; if (temp == head) cout<<"The list is circular linked list"<<endl; else cout<<"The list is not circular linked list"<<endl; } int main() { Node *head = new Node(2); head -> next = new Node(1); head -> next -> next = new Node(4); head -> next -> next -> next = new Node(3); head -> next -> next -> next -> next = new Node(6); head -> next -> next -> next -> next -> next = new Node(5); cout<<"The original list = "<<endl; print_list(head); cout<<"Check if the list is circular"<<endl;; check_if_list_is_circular_linked_list(head); make_linked_list_circular(head); cout<<"\n\nAfter making list as circular, check if the list is circular "<<endl; check_if_list_is_circular_linked_list(head); count_nodes_circular_linked_list(head); return 0; }
输出:
The original list = 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> Check if the list is circular The list is not circular linked list After making list as circular, check if the list is circular The list is circular linked list The total number of nodes in circular linked list is 6
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |