链表的回顾与总结(二)有序链表合并、约瑟夫问题

  1. 两个有序链表的合并
    在这里插入图片描述
#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;
}
//3 1 9 5 0
//7 4 2 9 8 3 16 0
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;
}
  1. 出圈(约瑟夫环问题)
    在这里插入图片描述
#include<iostream>
using namespace std;
struct node
{
	int num;
	node* next;
};//10 3
//4
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);//使q成为p的前驱结点
	//如果改成q->next=head的话,ide就会报错,“使用了未初始化的局部变量q”
	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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江星竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值