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

C++实现单链表的创建和打印

2016-04-16 21:23 549 查看
链接存储方法

 链接方式存储的线性表简称为链表(Linked List)。

 链表的具体存储表示为:

  ① 用一组任意的存储单元来存放线性表的结点(这组存储单元既可以是连续的,也可以是不连续的)

  ② 链表中结点的逻辑次序和物理次序不一定相同。为了能正确表示结点间的逻辑关系,在存储每个结点值的同时,

还必须存储指示其后继结点的地址(或位置)信息(称为指针(pointer)或链(link))

注意:

  链式存储是最常用的存储方式之一,它不仅可用来表示线性表,而且可用来表示各种非线性的数据结构。

关于链表的理论,在这里我就不做详解了。

创建简单链表的代码如下:

#include<iostream>
#include<string>
using namespace std;

struct Stu
{
int age;
string name;
struct Stu* next;
};

int main()
{
Stu s1,s2,s3;
Stu *p=&s1;

s1.age=22;
s1.name="天明";
s1.next=&s2;

s2.age=23;
s2.name="月儿";
s2.next=&s3;

s3.age=24;
s3.name="少羽";
s3.next=NULL;

for(int i=0;i<3;i++)
{
cout<<p->age<<" "<<p->name<<" "<<endl;
p=p->next;
}
return 0;
}


devc++中的运行截图:



当然了,我们写程序应该遵循“模块化”编程原则,即使用不同的函数实现不同的功能。这样的代码看起来才简洁明了,减小模块之间的影响(高内聚,低耦合)。

程序如下:

#include<iostream>
#include<malloc.h>
using namespace std;

struct Stu
{
int age;
string name;
struct Stu* next;
};

struct Stu* CreateList()
{
Stu *head;
head=(struct Stu*)malloc(sizeof(Stu));

Stu *p1,*p2;
if((p1=p2=(struct Stu*)malloc(sizeof(Stu)))==0)
{
cout<<"内存分配失败!"<<endl;
};

cout<<"提示:输入【0】结束输入!"<<endl;
cout<<"请输入年龄:";
cin>>p1->age;
if(p1->age==0)
{
return 0;
}
cout<<"请输入姓名:";
cin>>p1->name;

int i=0;
while(1)
{
i++;
if(i==1)
{
head=p1;
}

p2->next=p1;
p2=p1;

if((p1=(struct Stu*)malloc(sizeof(Stu)))==0)
{
cout<<"内存分配失败!"<<endl;
}
cout<<"请输入年龄:";
cin>>p1->age;
if(p1->age==0)
{
p2->next=NULL;
return head;
}
cout<<"请输入姓名:";
cin>>p1->name;
}
return head;
}

void ShowList(struct Stu* h)
{
while(h!=NULL)
{
cout<<h->age<<" "<<h->name<<" "<<endl;
h=h->next;
}
}

int main()
{
Stu *head=(struct Stu*)malloc(sizeof(Stu));

head=CreateList();
cout<<endl<<"你输入的内容为:"<<endl;
ShowList(head);
return 0;
}


运行截图如下:



注:本例中的程序都在devc++中通过了测试。

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