求一数据结构题的算法

来源:百度知道 编辑:UC知道 时间:2024/05/05 15:48:01
写一个对带头结点单循环链表进行遍历(打印每个结点的值)的算法,已知链表中任意结点的位置为P。

这条件也太不全了,
我假设一些吧。

假设链表结点的结构体定义如下:
struct Node
{
int data;
Node *next;
};

算法实现:
从p结点开始打印data值,直到遍历到p结束遍历。

void list(Node *p) //将p作为参数传入
{
Node *q=p;

while(q->next!=p)
{
printf("%d ",(*q).data);
q=q->next;
}

printf("%d ",(*q).data);//打印p之前的那个结点的data值
q=q->next;

}

#include "stdio.h"
#include<iostream>
//#include<stdlib>
using namespace std;

template <class T>
class Chain;
template <class T>
class ChainNode
{
friend Chain<T>;
private:
T data;
ChainNode<T> *link;
};
template<class T>
class Chain
{
public:
Chain()
{
head=new ChainNode<T>;//头节点
tail=head;
head->link=tail;
tail->link=head;
fir