1. 程式人生 > >關於資料結構之單鏈表的C++實現

關於資料結構之單鏈表的C++實現

1、連結串列List的基本單元是節點Node,因此想要操作方便,就必須為每一步打好基礎,Node的基本結構如下:
class Node
{
public:
int data;
Node *next;
Node(int da=0,Node *p=NULL)
{
this->data=da;
this->next=p;
}
};
我們可以看出,Node的成員變數一共有兩個,都是public,因為我們要對這兩個變數進行操作,所以不能是private型別的。然後是一個建構函式,第二個引數預設值為NULL,也就是說如果我們建立新節點時只指定第一個引數,而不寫第二個引數,那麼它預設的就是NULL,以這種方式可以更靈活的使用Node,個人建議這麼使用哦。
2、第二步就是建立我們的連結串列了,同樣我們這裡先給出連結串列的程式碼,在進行一一的解釋。
class List
{private:
Node *head,*tail;
int position;
public:
List()
{
head=tail=NULL;
};
~List()
{
delete head;delete tail;
};
void print();
void Insert(int da=0);
void Delete(int da=0);
void Search(int da=0);
};
我們這裡面有兩個資料型別,一個是Node。另一個是指代節點位置的成員變數(起不到什麼作用,且不去管它吧)。使用head和tail來命名便是為了見名知意,使操作更加準確。然後是重要的六個函式,各自的功能不言而喻咯,其實最重要的是在每一個函式中我們都預設能操作head和tail兩個成員變數,這樣能簡化我們的引數列表,使得函式更加優雅。
下面是我的一個單鏈表的實現,包含建立連結串列,插入值,刪除特定的值,查詢特定值得在連結串列中的位置。

#include
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int da=0,Node *p=NULL)
{
this->data=da;
this->next=p;
}
};
class List
{
private:
Node *head,*tail;
int position;
public:
List()
{
head=tail=NULL
};
~List()
{
delete head;
delete tail;
};
void print();
void Insert(int da=0);
void Delete(int da=0);
void Search(int da=0);
int getValueAt(int position);
void setValueAt(int position,int da);
};
int List::getValueAt(int position)
{
Node *p=head;
if(p=NULL)
{
cout<<“The List is Empty!”<<endl;
}
else
{
int posi=0;
while(p!=NULL&&posi!=position)
{
posi++;
p=p->next;
}
if(p=NULL)
{
cout<<“There is no value of this position in this List!”<<endl;
}
else
{
cout<<“In this Position,the value is”<data<<endl;
}
}
return p->data;
}
void List::setValueAt(int position,int da)
{
Node *p=head;
if(p== NULL)
{
cout<<“The List is Empty!”<<endl;
}
else
{
int posi=0;
while(p!=NULL&&posi!=position)
{
posi++; p=p->next;
}
if(p== NULL)
{
cout<<“There is No Position in this List!”<<endl;
}
else
{
p->data=da;
cout<<“The Value in this position has been Updated!”<<endl;
}
}}
void List::Search(int da)
{ Node *p=head;
if(p== NULL)
{
cout<<“Sorry, The List is Empty!”<<endl;
return ;
}
int count=0;
while(p!=NULL&&p->data!=da)
{
p=p->next; count++;
}
cout<<“the value you want to search is at position %d”<<count<<endl;}
void List::Delete(int da)
{
Node *p=head,*q=head;
if( p== NULL)
{
cout<<“Sorry, The List is Empty!”<<endl; return;
}
while(p!=NULL&&p->data!=da)
{
q=p; p=p->next;
}
q->next=p->next;
cout<<“The Deletion Operation had been finished!”<<endl;}
void List::Insert(int da)
{
if(head==NULL)
{
head=tail=new Node(da);
head->next=NULL;
tail->next=NULL;
}
else
{
Node *p=new Node(da);
tail->next=p;
tail=p;
tail->next=NULL;
}
}
void List::print()
{
Node *p=head;
while(p!=NULL)
{
cout<data<<" \a";
p=p->next; }
cout<<endl;}
int main()
{
cout<<“Hello World!”<<endl;
List l1;
l1.Insert(1);
l1.Insert(2);
l1.Insert(3);
l1.Insert(4);
l1.Insert(5);
l1.Insert(6);
l1.Insert(7);
l1.print();
l1.Search(4);
l1.Delete(6);
l1.print();
l1.getValueAt(3);
l1.setValueAt(3,9);
l1.print();
cout<<“The End!”<<endl;
return 0;
}