![]() |
#2
yangfrancis2018-01-28 21:35
|

#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
#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;
}
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;
}
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中,怎么设指针指向链表头?