當前位置:編程學習大全網 - 源碼下載 - 利用鏈表實現二路歸並排序算法。求完整的C++程序,急用今晚。

利用鏈表實現二路歸並排序算法。求完整的C++程序,急用今晚。

這個鏈表類裏包括增、刪、查、改,壹般來說應該夠用了吧,希望對妳有幫助。

把這裏面的函數名改壹改,再調用內部函數創建新的函數實現歸並、拆分應該不難。

template<typename T>

class List

{

private:

struct Node

{

T data;

Node* next;

Node(const T& t=T()):data(t)

{next=NULL;}

};

Node* head;

Node* getPointer(int pos)

{

Node* p=head;

for(int i=0;i<pos;i++)

p=p->next;

return p;

}

public:

List():head(NULL){};

void clear()

{

while(head!=NULL)

{

Node* p = head->next;

delete head;

head = p;

}

}

~List()

{

clear();

}

void insert_front(const T& t)

{

Node* p = new Node(t);

p->next = head;

head = p;

}

void travel()

{

Node* p = head;

while(p!=NULL)

{

cout<<p->data<<' ';

p = p->next;

}

cout<<endl;

}

void insert_back(const T& t)

{

Node* p = new Node(t);

if(head == 0)

head = p;

else

{

getPointer(size()-1) -> next = p;

}

}

int size()

{

int cnt = 0;

Node* p = head;

while(p != NULL)

{

cnt++;

p = p->next;

}

return cnt;

}

T getHead()

{

if(head == NULL)

throw "No Head";

return head->data;

}

T getTail()

{

if(head == NULL)

throw "No Tail";

Node* p = head;

while(p->next != NULL)

{

p = p->next;

}

return p->data;

}

bool empty()

{

return head==NULL;

}

int find(const T& t)

{

int pos = 0;

Node* p = head;

while(p!=NULL)

{

if(p->data == t)

return pos;

pos++;

p = p->next;

}

return -1;

}

bool updata(const T& o, const T& n)

{

int pos = find(o);

if(pos == -1)

return false;

Node* p = getPointer(pos);

p->data = n;

return true;

}

bool erase(const T& t)

{

int pos = find(t);

if(pos == -1)

return false;

if(pos == 0)

{

Node* p = head->next;

delete head;

head = p;

}

else

{

Node* pre = getPointer(pos-1);

Node* cur = pre->next;

pre->next = cur->next;

delete cur;

}

return true;

}

};

  • 上一篇:為什麽有人說大部分碼農做不了軟件架構師?
  • 下一篇:epc、pc、c分別是什麽承包合同?
  • copyright 2024編程學習大全網