双向链表

试设计一个算法,改造一个带表头结点的双向链表,所有结点的原有次序保持在各个结点的右链域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);
}
posted @ 2020-09-24 22:02  _Hsiung  阅读(121)  评论(0编辑  收藏  举报