注册 登录
编程论坛 C++教室

指针和类的问题

moox 发布于 2018-01-27 22:57, 1557 次点击
我定义了一个链表类,如下
程序代码:
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
template <typename T>
struct Node
{
    Node(T &x):data(x),next(0){}
    T data;
    Node<T> *next;
};

template <typename T>
class List
{
    Node<T> *head;
public:
    List();
    void insert(T &x);
    void remove(Node<T> *p);
    bool empty();
    ~List();
};
#endif // LIST_H_INCLUDED

程序代码:
template <typename T>
void List<T>::insert(T &x)
{
    Node<T> *pre=head;
    while(pre->next!=0)
    {
        pre=pre->next;
    }
    Node<T> newNode=new Node<T>(x);
    pre->next=newNode;
}

然后,给一个链表的实例,判断链表是否有环。大概如下
程序代码:
#include <iostream>

using namespace std;
#include"List.h"
bool hasCycle(List<int> *link){//判断链表有没有环
    if(link==0) return false;  //用两个指针pFast和pSlow遍历链表,如果两指针相等就有环
    Node<T> *pSlow=link,*pFast=link->next;//这儿错了,但不知道怎么改
    while(pSlow!=0||pFast!=0)
    {
        if(pSlow==pFast) return true;
        pSlow=pSlow->next;
        pFast=pFast->next;
        if(pFast==0) return false;
        pFast=pFast->next;
    }
    return false;
}

int main()
{
    List<int> link;
    for(int i=0;i<9;++i) link.insert(i);
    cout<<hasCycle(link);
    return 0;
}

结构体在class中,怎么设指针指向链表头?
1 回复
#2
yangfrancis2018-01-28 21:35
void GetHead(Node<T>*&h)
{
    h=head;
}
这样让h的实参指向表头。没测过,自己去试试看如何。
1