雙鏈表


#include <iostream>
#include <algorithm>
using namespace std;
struct node{
 int data;
 node *last,*next;
};
class doublel{
public:
    //雙鏈表的構造函數(非空的鏈表,輸入數據爲0,表示輸入結束)
    doublel(int a[],int n)
    {
        first=new node;
        first->next=NULL;
        first->last=NULL;
        for(int i=0;i<n;i++)
        {
           node *s;
           s=new node;
           s->data=a[i];
           s->next=first->next;
           first->next=s;
           s->last=first;
           if(s->next)
            s->next->last=s;



        }

    }
    //插入操作(將一個數據元素插入到有序的雙鏈表中,插入之後鏈表仍然有序,輸入數據爲0表示插入操作結束)
    void Insert(int x)
    {
        node *s,*d;
        s=new node;
        s->data=x;
        node *p;
        p=new node;
        p=first->next;
        while(p->next!=NULL&&p->data<x)
        {

            p=p->next;
        }
       s->next=p->next;
       p->next=s;
       s->last=p;
       if(s->next!=NULL)
        s->next->last=s;


    }
//    //按值刪除節點(考慮有重複值的情況)
//    void Delete(int x)
//    {
//        node *s,*p;
//        p=new node;
//        s=new node;
//        s=first->next;
//        while(s)
//        {
//            if(s->data==x)
//               {
//                   p=s;
//                  s->last->next=s->next;
//                  if(s->next)
//                  s->next->last=s->last;
//               }
//            s=s->next;
//            delete p;
//        }
//    }
//void Insert(int x)
//	{
//      node* s;
//		s = new node;
//		s->data = x;
//		node* p;
//		p = first;
//		while (p->next != NULL && p->next->data < x)
//		{
//			p = p->next;
//		}
//
//		s->next = p->next;
//		if(p->next!=NULL)
//			p->next->last = s;
//		s->last = p;
//		p->next = s;
//	}
	void Delete(int x)
	{
		node* p;
		p = first;
		while (p->next != NULL && p->next->data != x)
		{
			p = p->next;
		}
		while (p != NULL && p->next != NULL)
		{
			node* q;
			q = p->next;
			p->next = q->next;
			if(p->next!=NULL)
				q->next->last = p;
			delete q;
			if (p->next == NULL || p->next->data != x)
				break;
		}
	}
    //雙鏈表的遍歷操作
    void bl()
    {
        node *s;
        s=first->next;
        while(s)
        {
            cout<<s->data<<" ";
            s=s->next;
        }
        cout<<endl;
    }
private:
    node *first;
};

bool cmp(int a,int b){
    return a > b;
}

int main()
{  int num,c=0;
   int a[100];
   for(int i=0;i<100;i++)
   {


       cin>>num;
       if(num!=0)
       {
           a[i]=num;
           c++;
       }

       else
        break;
   }
   sort(a,a+c,cmp );
    doublel l(a,c);
    l.bl();
    while(true)
    {
        cin>>num;
        if(num==0)
            break;
          l.Insert(num);
    }

    l.bl();
    while(true)
    { cin>>num;
         if(num==0)
            break;
            l.Delete(num);
    }

    l.bl();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章