您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】 第二章 创建链表

2017-12-29 22:59 429 查看
前言

严蔚敏版数据结构、第二章 创建链表

看代码

//创建链表

//CreateList.cpp
//This program is to create two LNode and merge them into one创建两个结点合并成一个链表
# include <iostream>
# include <stdlib.h>
# include <malloc.h>//动态存储分配头文件
# include <conio.h>//console input/output控制台输入/输出头文件
using namespace std;//# include <iostream>和using namespace std;同时在vs里使用,cout不会报错
# define OK 1
# define ERROR 0

typedef struct LNode        //define the LNode structure结点
{
int data;
struct LNode *next;
}LNode, *LinkList;

int CreateList(LinkList &head, LinkList s, int x, int y)    //CreateList()创建链表
{
head = (LinkList)malloc(sizeof(LNode));
//为头结点分配内存空间并定义类型
if (!head)//判断是否分配成功
{
cout << endl << "Overflow ! The first LNode isn't allocated !";
return (ERROR);
}

s = (LinkList)malloc(sizeof(LNode));
//同理,为第二个节点执行相同的操作
if (!s)
{
cout << endl << "Overflow ! The second LNode isn't allocated !";
return (ERROR);
}
head->next = s;//指针指向下一个节点,形成链表
s->next = NULL;
head->data = x;//数据存储
s->data = y;
return (OK);
} //CreateList() end

void main()                 //main()  function
{
int x = 10, y = 15;
LNode L1, L2;//定义结点
LNode *p1, *p2;//定义指向结点的指针
p1 = &L1;
p2 = &L2;
cout << endl << endl << "CreateList.cpp";
cout << endl << "==============";
if (CreateList(p1, p2, x, y))       //call CreateList()调用链表创建函数
{
cout << endl << endl << "OK! The two LNode are : ";
cout << p1->data << "->" << p1->next->data;//对应链表创建函数里的next
}
cout << endl << endl << "...OK!...";
_getch();

} //main() end

//getch();使用时加下划线


思维导图



实现

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 链表