zoukankan      html  css  js  c++  java
  • 双向链表

    试设计一个算法,改造一个带表头结点的双向链表,所有结点的原有次序保持在各个结点的右链域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);
    }
    
  • 相关阅读:
    最长k可重区间集问题【网络流24题】
    分配问题 【网络流24题】
    航空路线问题 【网络流24题】
    最长不下降子序列问题 【网络流24题】
    数组去重
    项目选题报告(团队)
    关于DLL的创建与使用简单描述(C++、C#)
    原型设计(结对第一次)
    团队展示(团队)
    第二次作业——个人项目实战
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13811918.html
Copyright © 2011-2022 走看看