c++鏈表的初始化,頭插,尾插,遍歷

#include<iostream>
using namespace std;
//給數據類型起別名,方便統一管理
typedef int ELEMENT_TYPE;
// 定義單向鏈表的結點
typedef struct Node{
	ELEMENT_TYPE data;  //定義結點元素
	struct Node* next;  //定義指向下一個結點的指針
}Node;

Node* head;   //定義鏈表的頭結點

// 初始化鏈表的頭結點
void InitList(){
	head=new Node();
	head->next=NULL;
}

//採用頭插法插入結點
void InsertByHead(ELEMENT_TYPE element){
	Node* newNode=new Node();
	newNode->data=element;
	newNode->next=head->next;
	head->next=newNode;
}

//尾插法插入結點
void InsertByEnd(ELEMENT_TYPE element){
	Node* pre=head;
	Node* p=head->next;
	while(p!=NULL){
		pre=p;
		p=p->next;
	}
	Node* newNode=new Node();
	newNode->data=element;
	newNode->next=pre->next;
	pre->next=newNode;
}

//遍歷鏈表
void PrintList(){
	Node* p=head->next;
	while(p!=NULL){
		cout<<p->data<<"  ";
		p=p->next;
	}
	cout<<endl;
}

int main_list(){
	InitList();
	InsertByEnd(1);
	InsertByEnd(2);
	InsertByEnd(3);
	PrintList();
	system("pause");
	return 0;
}

發佈了47 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章