双向链表

试设计一个算法,改造一个带表头结点的双向链表,所有结点的原有次序保持在各个结点的右链域rLink中,并利用左链域ILink把所有结点按照其值从小到大的顺序连接起来。

#include<iostream>
using namespace std;
struct node
{
	int data;
	node* left, * right;
};
typedef node* list;
list init()
{
	list temp = new node;
	temp->left = temp->right = temp;
	return temp;
}
list locate(list l,int i, int d)
{
	if (l->right == l || i == 0) return l;
	list current;
	if (d == 0) current = l->left;
	else current = l->right;
	for (int j = 1; j < i; j++)
		if (current == l) break;
		else if (d == 0) current = current->left;
		else current = current->right;
	if (current != l) return current;
	else return NULL;
}
list insert(list l,int i, int x, int d)
{
	list current = locate(l,i,d);
	if (current == NULL) return false;
	list temp = new node;
	temp->data = x;
	if (d == 0)
	{
		temp->left =current->left ;
		current->left = temp;
		temp->left->right = temp;
		temp->right = current;
	}
	else
	{
		temp->right = current->right;
		current->right = temp;
		temp->right->left = temp;
		temp->left = current;
	}
	return l;
}
void print(list l)
{
	list st = l;
	while (l->right != st)
	{
		l = l->right;
		cout << l->data << " ";
	}
	cout << endl;
}
int length(list l)
{
	list current = l->right;
	int count = 0;
	while (current != l)
	{
		current = current->right;
		count++;
	}
	return count;
}
int main()
{
	list l = init();
	insert(l, 0, 3, 1);
	insert(l, 1, 5, 1);
	insert(l, 2, 2, 1);
	insert(l, 3, 1, 1);
	print(l);
	list ans = init();
	ans = insert(ans, 0, l->right->data, 1);
	list temp = l->right->right;
	while (temp != l)
	{
		int i = 0;
		list ans1 = ans->right;
		while (temp->data <= ans1->data)
		{
			ans1 = ans1->right;
			i++;
		}
		int leng = length(ans);
		ans = insert(ans, leng-i, temp->data, 0);
		temp = temp->right;
	}
	print(ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值