創建雙向鏈表類,該類有默認構造函數、類的拷貝函數、類的、實現鏈表添加數據、升序排序、查找鏈表中某個節點及刪除鏈表中某個節點的操作
代碼實現:
#include<iostream> #include<string.h> using namespace std; typedef int ElemData; struct node{ //節點類 ElemData data; node *next; node *prev; }; class LinkList //雙向鏈表類 { public: node *head;//指向頭結點 node *tail;//指向尾節點 int len;//鏈表長度 public: LinkList();//構造函數 LinkList(const LinkList &l);//拷貝函數 ~LinkList();//析構函數 void addNode(ElemData data);//往尾部添加元素 void upSort();//升序排序 void findNode(int n);//查找某個節點 void delNode(int n);//刪除某個節點 void showNode();//輸出所有節點數據 }; LinkList::LinkList() { head = NULL; tail = NULL; len = 0; } LinkList::LinkList(const LinkList &l) { if(l.head!=NULL) { node *pHc = l.head; head = new node();//為節點申請空間 head->data = pHc->data; len++; pHc = pHc->next; node *pH = head; while(pHc!=l.tail) { pH->next = new node(); len++; pH->data = pHc->data; pHc = pHc->next; } } else { head=tail=NULL; len = 0; } } LinkList::~LinkList() { node *bgn = head; while(head!=tail) { head = head->next; delete bgn;//釋放內存 bgn = head; } len = 0; } void LinkList::addNode(ElemData data) { if(head==NULL) { head = new node(); head->data = data; len++; tail = head; } else { tail->next = new node(); tail->next->data = data; len++; tail->next->prev = tail; tail = tail -> next; } } void LinkList::showNode() { node *p; p=head; if(p==NULL) cout<<"List id empty"<<endl; else { while(p!=tail->next) { cout<<p->data<<" "; p = p ->next; } cout<<endl; } } void LinkList::upSort() { node *p,*q; ElemData temp; for(p=head;p!=tail->next;p=p->next) { for(q=p->next;q!=tail->next;q=q->next) { if(p->data>q->data) { temp = p->data; p->data = q->data; q->data = temp; } } } } void LinkList::findNode(int n) { node *p; p = head; if(n>len) cout<<"超出鏈表長度"; else { for(int i=1;i<n;i++) { p = p->next; } cout<<"該節點是:"<<p->data<<endl; } } void LinkList::delNode(int n) { node *p,*q; p = head; q = head->next; if(n>len) cout<<"超出鏈表長度"; else { for(int i=2;i<n;i++) { p = p->next; q = q->next; } p->next = q->next; q->next->prev = p; delete q; } } int main() { int n; LinkList lin; cout<<"插入節點:"<<endl; lin.addNode(5); lin.addNode(8); lin.addNode(7); lin.addNode(4); lin.addNode(3); lin.addNode(4); lin.addNode(1); lin.addNode(0); lin.showNode(); lin.upSort(); cout<<"輸出所有節點:"<<endl; lin.showNode(); cout<<"輸入要查找第幾個節點:"<<endl; cin>>n; lin.findNode(n); cout<<"輸入要刪除第幾個節點:"<<endl; cin>>n; lin.delNode(n); lin.showNode(); return 0; }
實現效果圖: