循环列表设立头指针和尾指针

#include<iostream>
using namespace std;
typedef struct Lnode{
 int data;
 struct Lnode *next;
}Lnode,*Linklist;
int Init(Linklist& L){
 L=(Linklist)malloc(sizeof(Lnode));
 if(!L)return -1;
 L->next=L;
  L->data=NULL;
 return 0;
}
int shuru(int m,Linklist&L){
 Linklist A=L;
 for(int i=0;i<m;i++){
  int j;
  cout<<i+1<<":";
  cin>>j;
  Linklist S;
  S=(Linklist)malloc(sizeof(Lnode));
  S->data=j;
  A->next=S;
  S->next=L;
  A=S;
 }
return 0;
}
int shuchu(Linklist &L){
 Linklist A=L->next;
 while(A->next->data){
 cout<<A->data<<"-->";
 A=A->next;
 }
 cout<<A->data;
 return 0;
}
int wei(Linklist L,Linklist &wei){
 Linklist A=L->next;
 while(A->next->data){
  A=A->next;
 }
  wei=A;
 return 0;
}
int hebin(Linklist &wei1,Linklist& wei2,Linklist L1,Linklist L2)
{
wei1->next=L2->next;
wei2->next=L1;
return 0;
}

int main(){
 Linklist L;
 int j;
 Init(L);
 cout<<"输入的个数"<<endl;
 cin>>j;
 shuru(j,L);
 shuchu(L);
 Linklist S;
 Init(S);
 cout<<endl;
 cout<<"输入的个数"<<endl;
 cin>>j;
 shuru(j,S);
 shuchu(S);
 cout<<endl;
Linklist wei1,wei2;
wei(L,wei1);
wei(S,wei2);
hebin(wei1,wei2,L,S);
shuchu(L);
cout<<endl;
 return 0;
}

 

在Python中,使用带结点的循环链表表示队列,仅保留一个指针`tail`指向队尾元素,而不设立专门的指针,可以简化实现,但会增加一些操作的复杂性。这是因为当我们需要访问队首元素时,需要从队尾开始向前遍历直到找到第一个元素。以下是基本的实现步骤: 1. 定义一个`Node`类,用于存储链表节点,包含数据指向下一个节点的引用。 2. 创建一个`CircularQueue`类,维护一个`tail`指针,代表队尾元素。 - 初始化函数`__init__`设置初始状态为空队列。 - `enqueue`方法用于入队,将新节点作为新的队尾,然后更新`tail`。 - `dequeue`方法用于出队,从当前队尾开始遍历到队首元素,删除之并返回值,同时处理尾指针更新。 - `is_empty`方法检查队列是否为空,即`tail`是否为None。 - `size`方法计算队列大小,通过遍历到队首再回溯到队尾计数。 下面是一个简单的实现例子: ```python class Node: def __init__(self, data=None): self.data = data self.next = None class CircularQueue: def __init__(self): self.tail = Node() # 带结点的循环链表 def enqueue(self, item): new_node = Node(item) if not self.is_empty(): current_tail = self.tail while current_tail.next != self.tail: current_tail = current_tail.next current_tail.next = new_node else: new_node.next = self.tail self.tail = new_node def dequeue(self): if self.is_empty(): raise Exception("Queue is empty") else: if self.tail.next == self.tail: self.tail = None else: current_tail = self.tail while current_tail.next != self.tail: current_tail = current_tail.next current_tail.next = self.tail.next return self.tail.data def is_empty(self): return self.tail == None def size(self): count = 0 current = self.tail.next while current != self.tail: count += 1 current = current.next return count # 示例 cq = CircularQueue() cq.enqueue(1) cq.enqueue(2) print(cq.dequeue()) # 输出:1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值