您的位置:首页 > 编程语言 > C语言/C++

c++链表的初始化,头插,尾插,遍历

2014-09-12 10:30 176 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: