- 两个有序链表的合并
#include<iostream>
using namespace std;
struct node
{
int num;
node* next;
};
void show(node* head)
{
while (head)
{
cout << head->num << ' ';
head = head->next;
}
}
void add(node* head1, node* head2,node*&head3)
{
head3 = head1->num < head2->num?head1 : head2;
node* last = head3;
if (head1->num < head2->num)
head1 = head1->next;
else head2 = head2->next;
while (1)
{
if (head1->num < head2->num)
{
last->next = head1;
last = head1;
head1 = head1->next;
}
else {
last->next = head2;
last = head2;
head2 = head2->next;
}
if (head1 == NULL)
{
last->next = head2;
break;
}
else if (head2 == NULL)
{
last->next = head1;
break;
}
}
}
void insert(node*& head, int n)
{
node* s, * q, * p;
s = new node;
s->num = n;
s->next = NULL;
if (head == NULL)
{
head = s;
return;
}
if (head->num > s->num)
{
s->next = head;
head = s;
return;
}
for (q = head, p = head->next; p; q = p, p = p->next)
{
if (p->num > s->num)
{
s->next = p;
q->next = s;
return;
}
}
q->next = s;
return;
}
int main()
{
int n, i, j, k, m;
node* head1 = NULL;
cin >> k;
while (k != 0)
{
insert(head1, k);
cin >> k;
}
show(head1);
cout << endl;
node* head2 = NULL;
cin >> j;
while (j != 0)
{
insert(head2, j);
cin >> j;
}
show(head2);
cout << endl;
node* head3 = NULL;
add(head1,head2,head3);
show(head3);
return 0;
}
- 出圈(约瑟夫环问题)
#include<iostream>
using namespace std;
struct node
{
int num;
node* next;
};
void create(node*& head, int n)
{
node* q, * p;
int i;
head = new node;
p = head;
for (i = 1; i <= n; i++)
{
p->num = i;
if (i < n)
{
p->next = new node;
p = p->next;
}
}
p->next = head;
}
void out(node*& head,int m)
{
node* q, * p = head;
int k;
for (q = head; q->next != head; q = q->next);
while (p != p->next)
{
for (k = 1; k < m; k++)
{
q = p;
p = p->next;
}
q->next = p->next;
delete p;
p = NULL;
p = q->next;
}cout << p->num << endl;
delete p;
p = NULL;
}
int main()
{
node* head;
int n, m;
while (cin >> n >> m) {
create(head,n);
out(head, m);
}
return 0;
}