博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
循环链表的插入和删除
阅读量:7227 次
发布时间:2019-06-29

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

  hot3.png

循环链表可以用来使计算机处理内存工作区或输出至数据缓冲区。

循环链表的插入和删除

 
#include " iostream "
#include
" stdlib.h "
using namespace std;
struct clist
{
int data;
struct clist * next;
};
typedef
struct clist cnode;
typedef cnode
* clink;
/* -----循环链表的输出------ */
void printclist( clink head)
{
clink ptr;
head
= head -> next;
ptr
= head;
do
{
printf(
" [%d] " ,ptr -> data);
ptr
= ptr -> next;
}
while (head != ptr && head != head -> next);
printf(
" \n " );
}
/* -----循环链表的结点插入---- */
clink insertnode(clink head,clink ptr,
int value)
{
clink new_node;
new_node
= (clink) malloc( sizeof (cnode));
if ( ! new_node)
return NULL;
new_node
-> data = value;
new_node
-> next = NULL;
if (head == NULL)
{
new_node
-> next = new_node;
return new_node;
}
if (ptr == NULL)
{
/* ----情况1:插在第一结点之前--- */
new_node
-> next = head -> next;
head
-> next -> next = new_node;
}
else
{
/* -----情况2:插在结点之后------- */
new_node
-> next = ptr -> next;
ptr
-> next = new_node;
}
if (ptr == head)
head
= new_node;
return head;
}
/* ---循环链表结点删除--- */
clink deletenode(clink head,clink ptr)
{
clink previous;
if (head == NULL)
{
/* ----情况1:删除第一个结点---- */
head
-> next = ptr -> next;
}
else
{
/* --情况2:删除中间结点--- */
previous
= head;
if (head != head -> next)
while (previous -> next != ptr)
previous
= previous -> next;
previous
-> next = ptr -> next;
}
if (ptr == head)
head
= previous;
free(ptr);
return head;
}
/* 使用插入结点的方式来创建链表,完成后将链表内容输出,然后删除前后两结点 */
int main()
{
clink head
= NULL;
int list[ 6 ] = {
9 , 7 , 3 , 4 , 5 , 6 };
int i;
head
= insertnode(head,head,list[ 0 ]);
printf(
" 创建第一个结点: " );
printclist(head);
/* ---情况1:插在第一结点前---- */
head
= insertnode(head,NULL,list[ 1 ]);
printf(
" 插入第一结点之前: " );
printclist(head);
for (i = 2 ;i < 6 ;i ++ )
{
/* ---情况2:插在结点之后----- */
head
= insertnode(head,head -> next,list[i]);
printf(
" 插入结点之后: " );
printclist(head);
}
/* ---情况1:删除第一个结点--- */
head
= deletenode(head,head -> next);
printf(
" 删除第一个结点: " );
printclist(head);
/* --删除最后一个结点-- */
printf(
" 删除最后一个结点: " );
head
= deletenode(head,head);
printclist(head);
}

 

转载于:https://my.oschina.net/garyun/blog/602945

你可能感兴趣的文章
Python学习教程(Python学习路线):Python 3—手动创建迭代器
查看>>
说说如何在 Virtual Box 中新建 CentOS 虚拟机
查看>>
Cordova + Vue 实现点击两次退出应用
查看>>
JAVA 多用户商城系统b2b2c-Spring Cloud Stream 介绍
查看>>
spring cloud构建互联网分布式微服务云平台-SpringCloud集成项目简介
查看>>
基于房源的画像分析
查看>>
80% UI 初学者走过的弯路,你走了几条?
查看>>
文档和元素的几何滚动
查看>>
php 设计模式
查看>>
Java springcloud B2B2C o2o多用户商城 springcloud架构(八)springboot整合mongodb
查看>>
3年工作经验的Java程序员面试经过
查看>>
Mysql 批量写入数据,对于这类性能问题,你是如何优化的
查看>>
MySQL无法启动几种常见问题小结
查看>>
阿里CTO:阿里所有技术和产品输出都将必须通过阿里云进行
查看>>
更好用的集群限流功能,Sentinel 发布 v1.4.2
查看>>
Python(生成执行文件)
查看>>
redis安装配置 - ttlsa教程系列之redis
查看>>
Linux --DHCP服务器配置;DHCP服务器中继
查看>>
IE版本多的可爱_已迁移
查看>>
eclipse查看jar包中class的中文注释乱码问题的解决
查看>>