# double list

198人阅读 评论(0)

#ifndef LIST_H_
#define LIST_H_

struct Node
{
int data;
Node *next;
Node *pre;
Node(int d){ data = d; }
};

class List
{
public:
List();
List(int *arr, int size);    //根据数组构造链表
~List();
void display();              //从头显示链表
void display(int);           //从尾显示链表
Node *find(const int num);   //寻找元素num,返回对应结点，没找到返回NULL
void transfer(Node *position, Node *first, Node *last);    //将结点[first,last)之间的元素移动到position节点之前,注意是前开后闭
void merge(List &list);      //两个递增的链表合并成一个递增的链表
void reverse();              //反转链表
void swap(List &list);       //交换链表
void sort();                 //排序
private:
Node *tail;
};

#endif

#include "list.h"
#include <iostream>
using namespace std;
List::List()
{
}

List::List(int *arr, int size)
{
tail = new Node(0);
if (size == 0) return;
Node *p = NULL, *f = tail;
for (int i = 0; i < size; i++)
{
Node *temp = new Node(arr[i]);
if (i == 0)	head->next = temp;
else
{
p->next = temp;
p->pre = f;
f = p;
}
p = temp;
}
p->next = tail;
p->pre = f;
tail->pre=p;
}

List::~List()
{
{
}
}

void List::display()
{
while (p != tail)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}

void List::display(int)
{
Node *p = tail->pre;
while (p != tail)
{
cout << p->data << " ";
p = p->pre;
}
cout << endl;
}

Node *List::find(int num)
{
while (p != tail)
{
if (p->data == num) return p;
p = p->next;
}
return NULL;
}

void List::transfer(Node *position, Node *first, Node *last)
{
if (position != last)
{
last->pre->next = position;            //(1)
position->pre->next = first;           //(2)
first->pre->next = last;               //(3)
//此处不能这样：first->pre=position->pre;如果这样，first原来的pre就丢了，所以不需有个temp
Node *temp = position->pre;            //(4)
position->pre = last->pre;             //(5)
last->pre = first->pre;                //(6)
first->pre = temp;                     //(7)
}
}

void List::merge(List &list)
{
Node *p1 = head->next, *p2 = tail2->next;

while (p1 != tail && p2 != tail2)
{
if (p2->data < p1->data)
{
Node *n = p2;
n = n->next;
transfer(p1, p2, n);
p2 = n;
}
else p1 = p1->next;
}
if (p2 != tail2) transfer(p1, p2, tail2);
}

void List::reverse()
{
while (p->next != tail)	transfer(p, tail->pre, tail);
}

void List::swap(List &list)
{
}

void List::sort()
{
List carry;
List counter[64];
int fill = 0;
{
int i = 0;
{
counter[i].merge(carry);
carry.swap(counter[i++]);
}
carry.swap(counter[i]);
if (i == fill) ++fill;
}
for (int i = 1; i < fill; i++)
counter[i].merge(counter[i-1]);
swap(counter[fill - 1]);
}

#include <iostream>
#include "list.h"
using namespace std;

int main()
{
int arr[] = {1,3,5,7,9};
List myList1(arr,5);
int arr2[] = { 2, 4, 6, 8 ,10};
List myList2(arr2,5);
//myList1.merge(myList2);
//myList1.display();
//myList1.reverse();
myList1.sort();
myList1.display();
return 0;
}

欢迎订阅公众号：IT程序员开发
欢迎订阅公众号：IT程序员开发
个人资料
等级：
访问量： 8万+
积分： 2935
排名： 1万+
最新评论