// 通过子函数调用创建链表的三种方式
#include "stdafx.h"
#include <iostream>
using namespace std;
struct node{
int value;
node* next;
};
node* createList();
void createList1(node* head);
void createList2(node*& head);
void printList(node* head);
int _tmain(int argc, _TCHAR* argv[])
{
// 创建链表方式1,在子函数中创建链表,返回头指针
//node* head = createList();
//printList(head);
// 创建链表方式2,在主函数中创建头结点
// 不需要返回值,不需要引用传递
//node* head1 = new node();
//head1->value = -1;
//head1->next = NULL;
//createList1(head1);
//printList(head1);
// 创建链表方式3,在主函数中定义头结点,仅仅是定义
// 不需要返回值,但要使用引用传递
node* head2;
createList2(head2);
printList(head2);
system("pause");
return 0;
}
// 方式1:在子函数中创建链表,返回头指针
node* createList(){
node* head = new node();
head->value = -1;
head->next = NULL;
for(int i=0;i<100;i++){
node* newnode = new node();
newnode->value = i;
// 头插
newnode->next = head->next;
head->next = newnode;
}
return head;
}
// 方式2:在主函数中创建头结点,头指针指向已经明确,不需要子函数再去修改头指针的指向,所以不需要head的引用传递
void createList1(node* head){
for(int i=0;i<100;i++){
node* newnode = new node();
newnode->value = i;
// 头插
newnode->next = head->next;
head->next = newnode;
}
}
// 方式3::仅仅在主函数中定义了头指针,但并未开辟内存,需要子函数改掉头指针的指向,所以需要head的引用传递,但不需要返回值
void createList2(node*& head){
head = new node();
for(int i=0;i<100;i++){
node* newnode = new node();
newnode->value = i;
// 头插
newnode->next = head->next;
head->next = newnode;
}
}
// 打印链表
void printList(node* head){
node* ptr = head->next;
while(ptr!=NULL){
cout<<ptr->value<<" ";
ptr = ptr->next;
}
}
创建链表的三种方式:
1.在子函数中定义头结点并为头结点开辟空间,将新的数据结点链接在头结点之后,最后返回头结点指针。
2.在主函数中定义头结点并为头结点开辟空间,此时头结点已经创建好,只需要将头结点指针传给子函数即可,子函数调用结束后长长的链表自然就被创建好了。
3.只在主函数中定义头结点,但并不开辟空间,此时头结点指针还没有被赋予初值,将头指针的的引用传给子函数,子函数为头结点开辟空间之后,自然就把主函数中定义的头指针给改了,让头指针指向子函数开辟的空间。
以上三种方法我认为第一种比较好,将整个创建的链表的过程封装在子函数中,最后只返回一个创建好的链表的头指针。在创建二叉树,图的例子中跟这个是完全相仿的。
比较容易让人迷惑的是第三种方式,主函数定义头指针后并未开辟空间,此时head的指向还不明确,但子函数为head开辟过空间之后head的指向就被确定下来,所以需要在子函数中改掉头指针的指向,指针本质就是一个表示内存地址的长整数,因为要在子函数中改掉这个长整数,这就需要用到引用传递。