博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单链表的构建
阅读量:2810 次
发布时间:2019-05-13

本文共 2111 字,大约阅读时间需要 7 分钟。

        链表可以没有头结点,但是不能没有头指针.

        单链表中第一个结点的存储位置叫做头指针,最后一个结点的指针域为空,但是有数据域.整个链表的存取从头指针开始.如果链表有头结点,那么头指针就是指向头结点数据域的指针,如下图所示:

在这里插入图片描述

        没有头结点的单链表如下所示;

在这里插入图片描述

**

注意:

**

①头结点是为了操作方便和统一设立的,它的数据域一般无意义(存储链表一些信息).
②无论链表是否为空,头指针都不为空.

#include 
using namespace std;struct node{ int data; struct node *next;};**//尾插法构建不带头结点的单链表**struct node * creat_wf(int n){ struct node *head; struct node *p,*q; head = NULL; for(int i=0;i
>p->data; if(head == NULL) head = p; else q->next = p; q=p; } q->next = NULL; return head;}**//尾插法构建带头结点的单链表**struct node * creat_wt(int n){ struct node *head; struct node *p,*q;//尾插法中必须有一个尾指针始终指向当前链表的尾结点 //创建头结点 **//****头结点的作用:①在链表第一个位置上的操作和其他位置一样,不需要进行特殊处理 ②无论链表是否为空,其头指针都是指向头结点的非空指针,因此空表和非空表的处理统一** p=(struct node *)malloc(sizeof(struct node)); cin>>p->data; head=p; //构建其他结点 for(int i=1;i
>q->data; p->next = q; p=q; } p->next = NULL; return head;}**//头插法构建单链表**struct node * creat_t(int n){ struct node *head; struct node *p; head=NULL; for(int i=0;i
>p->data; p->next=head; head=p; } return head;}**//输出链表**void out_l(struct node *head){ struct node *h=head; while(h) { cout<
data<
next; }}int main(){ int n; cin>>n; struct node *head=creat_wt(n); out_l(head); struct node *head1=creat_t(n); out_l(head1); struct node *head2=creat_wt(n); out_l(head2); return 0;}

动态创建链表并且进行测试:

#include 
using namespace std;struct ListNode{ int val; struct ListNode *next;};int main(){ struct ListNode *head; struct ListNode *p,*q; head=NULL; int n; while(cin>>n)//输入一串字符后,回车换行符也被存在缓冲区 { p = (struct ListNode *) malloc(sizeof(struct ListNode)); p->val=n; if (head == NULL) head = p; else q->next = p; q = p; if(cin.get()=='\n')//判断缓冲区是否为回车符 break; } q->next=NULL; while(head) { cout << head->val << endl; head = head->next; }}

在这里插入图片描述

转载地址:http://zyzqd.baihongyu.com/

你可能感兴趣的文章
nrm(npm镜像管理工具)
查看>>
1064 朋友数 (20 分)
查看>>
1043 输出PATest (20 分)
查看>>
1056 组合数的和 (15 分)
查看>>
Web前端性能优化
查看>>
雅虎前端优化的35条军规
查看>>
webpack学习视频笔记整理
查看>>
31 天重构学习笔记索引
查看>>
Web前端开发最佳实践(1):前端开发概述
查看>>
关于前后端交互加密传输问题
查看>>
前端技术教程及文档
查看>>
Hadoop学习路线图
查看>>
netty长连接实例
查看>>
优化SQL查询:如何写出高性能SQL语句
查看>>
mysql优化方案总结
查看>>
Spring中jdbcTemplate的用法实例(一)
查看>>
用Quartz处理定时执行的任务
查看>>
quartz定时器demo类
查看>>
SpringBoot请求参数校验和接口参数校验
查看>>
使用synchronized小坑
查看>>