天天看點

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;
}
           

繼續閱讀