#ifndef CYCLICLIST_H_
#define CYCLICLIST_H_
#include <iostream>
using namespace std;
class CyclicList
{
public:
/* public标示外部代码可见 */
struct node
{
int dat;
struct node* next;
};
/*
* 向循环单链表中插入新元素,保持链表元素有序,升序。
* 1. 遍历链表找到正确的插入位置是关键。
* 2. cur,nxt之间的位置就是要插入的位置。
* 3. 插入最小值时需要修改head,链表升序,head指向最小值。
* 4. 测试数据
1 2 3 4 5
1 1 1 1 5
1 2 3 4 0
1 1 1 2 0
1 2 3 9 5
*
*/
void insert(struct node* &head, int x)
{
if (NULL == head)
{
struct node *p = new struct node();
p->dat = x; p->next = p;
head = p; /* 这一句不要漏掉 */
return;
}
struct node *cur, *nxt; /* 使用debug 调试的时候看不到这些局部变量是怎么回事?? */
cur = head; nxt = head->next;
/* 遍历循环链表找到正确的位置 */
do
{
if ((x >= cur->dat && x < nxt->dat) && (cur->dat < nxt->dat)) break; /* 正常情况 */
if ((x >= cur->dat) &&
单向循环链表的有序插入 对单向循环链表head插入元素 链表保持有序
最新推荐文章于 2022-11-20 15:00:23 发布
本文介绍如何在保持升序的单向循环链表中插入新元素。通过遍历链表找到正确插入位置,详细解释了不同情况的处理,包括最小值插入时更新头节点。同时提供了一个简单的链表释放函数,但指出可能存在内存泄漏问题。
摘要由CSDN通过智能技术生成