数据结构 单链表 (C++)(转载)
生活随笔
收集整理的這篇文章主要介紹了
数据结构 单链表 (C++)(转载)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線性表包含 數據域和指針域 其中,data存儲數據本身的值,next存儲后繼元素的地址 下面的圖表示的是一個數據節點
單鏈表的結構示意圖(包括空的單鏈表):
?
?
?
?
?
?
?
if(head==NULL||i<0)//頭插入(單鏈表為空或者)
{
q=new Node<T>(x,head);
head=q;
}
Node<T>* SinglyLinkedList<T>::insert(int i,T x)
{
Node<T> *q=NULL;
if(head==NULL||i<0)//頭插入(單鏈表為空或者)
{
q=new Node<T>(x,head);
head=q;
}
else
{
int j=0;
Node<T> *p=head;
while(p->next!=NULL&&j<i-1)
{
j++;
p=p->next;
}
q=new Node<T>(x,p->next);
p->next=q;
}
return q;
}
template<class T>
SinglyLinkedList<T>::SinglyLinkedList(T table[],int n)
{
head=NULL;
if(n>0)
{
head=new Node<T>(table[0]);//創建節點
Node<T> *rear=head;//創建一個指向頭節點的指針
int i=1;
while(i<n)
{
rear->next=new Node<T>(table[i++]);
rear=rear->next;
}
}
}
head=head->next;
delete q;
if(q!=NULL)//判斷刪除節點
{
p->next=q->next;//讓刪除節點的前驅Next指針下一節點
delete q;//刪除該節點
}
bool SinglyLinkedList<T>::remove(int i,T &old)
{
if(i<0||head==NULL)
{
Node<T> *q=head;
old=q->data;
head=head->next;
delete q;
}
else
{
Node<T> *p=getNode(i-1);//獲取刪除節點的前驅
if(p!=NULL&&p->next!=NULL)//判斷刪除節點和刪除節點是否為空
{
Node<T> *q=p->next;//新建一個節點指針,將刪除接點復制過去
old=q->data;
p->next=q->next;//讓刪除節點的前驅Next指針下一節點
delete q;//刪除該節點
return true;
}
}
return false;
}
void SinglyLinkedList<T>::concat(SinglyLinkedList<T> &list)
{
if(this->head==NULL)
{
this->head=list->head;
}
else
{
Node<T> *p=head;
while(p->next!=NULL)
{
p=p->next;
}
p=list->head;
}
list->head=NULL;//設置單鏈表為空,否則運行出錯
}
以上對C++單鏈表的分析 添加一個學生結構和一個測試函數:
Student.h
struct Student {char number[10]; //學號char name[20]; //姓名double score; //得分friend std::ostream& operator<<(std::ostream& out,Student &stu){out<<"學號:"<<stu.number<<" 姓名:"<<stu.name<<" 得分:"<<stu.score;return out;} };?
主函數:
#include<iostream> #include "SinglyLinkedList.h" #include "Student.h" void _TestToSinglyLinkedList() {Student data[]={{"090313018","Silvester",45.4},{"090313018","捐贈",45.4},{"090313018","版主",45.6}};SinglyLinkedList<Student> m(data,3);Student t;std::cout<<(m.isEmpty()?"不為空!":"該鏈表為空!")<<std::endl;std::cout<<"長度:"<<m.length()<<std::endl;std::cout<<"移除2個學生"<<m.remove(1,t)<<std::endl;std::cout<<"t:"<<t<<std::endl;std::cout<<"2個學生信息"<<m.getNode(1)<<std::endl;Student s={"415646","fdsfs",453.1};std::cout<<m.get(1)<<m.set(1,s)<<m.insert(5,s)<<std::endl; } void main() {_TestToSinglyLinkedList();system("pause"); }?
?提供源代碼下載地址:http://39327.42la.com.cn/DataFile/Code/C++/SinglyLinkedList.zip
轉載于:https://www.cnblogs.com/cosmo89929/archive/2013/03/04/2942567.html
總結
以上是生活随笔為你收集整理的数据结构 单链表 (C++)(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringCloud微服务(05):Z
- 下一篇: ORACLE新建表空间