#include<iostream>
#include<vector>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
class BSNode
{
public:
int data;
BSNode* next;
BSNode* before;
};
Node* create(int n)
{
Node* head = NULL;
Node* one = NULL;
Node* p = NULL;
for (int i = 1; i <= n; i++)
{
one = new Node;
cin >> one->data;
if (head == NULL)
{
head = one;
p = one;
}
else
{
p->next = one;
p = one;
}
}
p->next = NULL;
return head;
}
void print(Node* head)
{
Node* p;
p = head;
int count = 0;
while (p)
{
if (count != 0)
cout << "->";
cout << "["<<p->data <<"]";
p = p->next;
count++;
}
}
int get_sum(Node* head)
{
Node* p;
p = head;
int sum = 0;
while (p)
{
sum += p->data;
p = p->next;
}
return sum;
}
vector<int> getsorted(Node* head)
{
vector<int> nums;
Node* p;
p = head;
while (p)
{
nums.push_back(p->data);
p = p->next;
}
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[j] < nums[i])
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
}
return nums;
}
int get_Max(Node *head)
{
vector<int> nums = getsorted(head);
return nums[nums.size() - 1];
}
int get_Min(Node* head)
{
vector<int> nums = getsorted(head);
return nums[0];
}
int get_len(Node* head)
{
vector<int> nums = getsorted(head);
return nums.size();
}
Node* sort_Node(Node* head)
{
vector<int> nums = getsorted(head);
Node* head1 = NULL;
Node* one = NULL;
struct Node* p = NULL;
for (int i = 0; i < nums.size(); i++)
{
one = new Node;
one->data = nums[i];
if (head1 == NULL)
{
head1 = one;
p = one;
}
else
{
p->next = one;
p = one;
}
}
p->next = NULL;
return head1;
}
BSNode* create_BSNode(Node* head0)
{
Node* p0 = head0;
BSNode* head=NULL;
BSNode* p=NULL;
BSNode* q = NULL;
BSNode* one = NULL;
while (p0)
{
one = new BSNode;
one->data = p0->data;
if (head == NULL)
{
head = one;
p = one;
}
else
{
p->next = one;
q = p;
p = one;
p->before = q;
}
p0 = p0->next;
}
p->next = head;
head->before = p;
return head;
}
void read_BSNode(BSNode* head)
{
BSNode* p = head;
int count = 0;
do
{
if (count != 0)
cout << "->";
cout << "[" << p->data << "]";
count++;
p = p->next;
} while (p!=head);
}
void search_BSNode(BSNode* head, int val)
{
BSNode* p = head;
if (head->data == val)
{
read_BSNode(head);
}
do
{
if (p->data == val)
break;
p = p->next;
} while (p != head);
if (p != head)
{
read_BSNode(p);
}
else
{
cout << "链表中没有该结点" << endl;
}
}
int main()
{
int n;
cout << "请输入结点个数" << endl;
cin >> n;
Node* head1 = create(n);
print(head1);
cout << endl << "最大值:" << get_Max(head1) << "\t" << "最小值:" << get_Min(head1) << endl;
Node* head2=sort_Node(head1);
cout << endl << "排序后" << endl;
print(head2);
cout <<endl<< "长度:" << get_len(head2) << endl;
cout << "数据域之和:" << get_sum(head2);
cout << endl<<endl;
cout << "双向循环链表:" << endl;
BSNode* head3 = create_BSNode(head1);
read_BSNode(head3);
int num;
cout <<endl<< "请输入要查找结点的数据" << endl;
cin >> num;
search_BSNode(head3, num);
return 0;
}
由单链表生成双向循环链表
最新推荐文章于 2022-11-28 20:38:35 发布