typedef struct node //定義鏈表節(jié)點相關結構體
{int data;
struct node *next;
node(int x) : //構造函數(shù),用于在創(chuàng)建對象時初始化對象的各個成員
data(x), next(NULL){}
}Node;
定義鏈表結構體struct linklist //定義鏈表結構體
{public:
void create()
{head = new Node(0); //初始化頭節(jié)點,即調用了上面的構造函數(shù),使head->data=0,head->next=NULL
if(head == NULL) //內存已滿的情況下,無法給頭節(jié)點分配地址,報錯
{ cout<< "new failed"<< endl;
return;
}
}
void insert(int m_data) //頭插法
{Node *m_new = new Node(0); //創(chuàng)建一個新的節(jié)點
if(m_new == NULL)
{ cout<< "new failed"<< endl;
return;
}
m_new->data = m_data;
m_new->next = NULL; //這條語句可以省略
m_new->next = head->next; //將新節(jié)點插入到頭節(jié)點后
head->next = m_new;
}
void show()
{Node *p = head->next;
while(p != NULL) //循環(huán)遍歷鏈表打印每一個節(jié)點數(shù)據(jù)
{ cout<< p->data<< " ";
p = p->next;
}
cout<< endl; //換行
}
private:
Node *head;
};
上面這一串代碼建立了鏈表結構體,但其中insert采用的是頭插法,下面展示一下尾插法該怎么寫
void insert(int m_data) //尾插法
{Node *m_new = head; //創(chuàng)建一個新的節(jié)點并指向頭節(jié)點
Node *p = new node(0);
if(p== NULL)
{ cout<< "new failed"<< endl;
return ;
}
while(m_new->next!=NULL){//使m_new指針指向最后一個節(jié)點
m_new = m_new->next;
}
m_new->next = p;
p->data = m_data;
}
在主函數(shù)中進行調用int main()
{struct linklist list;
list.create();
int n = 10;
while(n--)
{list.insert(n);
}
list.show();
return 0;
}
你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
本文名稱:【C++】鏈表的定義及其基本操作-創(chuàng)新互聯(lián)
本文來源:http://jinyejixie.com/article24/eipje.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、建站公司、標簽優(yōu)化、靜態(tài)網(wǎng)站、外貿(mào)網(wǎng)站建設、App設計
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容