筆試程序題專項----鏈表是否存在環

思路:

代碼:

#include <stdio.h>
#include<stdlib.h>
#include<iostream>
#include<stack>
using namespace std;
#define SUCCESS 1000001
#define FAILURE 1000002
typedef int ElemType;

struct node
{
    ElemType data;
    struct node *next;
};

typedef struct node Node;
typedef Node *LinkList;
int ListInit(LinkList *L);
int ListInsert(LinkList *L,int i,ElemType e);
int ListTraverse(LinkList L,ElemType(*print)(ElemType));
ElemType visit(ElemType e);
bool isCir(LinkList L)
{
    LinkList pslow,pfast;
    pslow=pfast=L->next;
    if(pfast==NULL) return false;
    pfast=pfast->next;
    while(pfast!=NULL)
    {
        if(pfast==pslow)
            return true;
        pslow=pslow->next;

        pfast=pfast->next;
        if(pfast!=NULL)
            pfast=pfast->next;
    }
    return false;
}
int main()
{
    int ret,i;
    LinkList list,p,p2;
    int place;
    ElemType e;
    ret = ListInit(&list);
    for(i = 0; i < 10; i++)
    {
        ret = ListInsert(&list,i+1,i);
    }
    p=list->next;
    p2=p->next;
    for(int i = 0; i <9; i++)
        p=p->next;
    p->next=p2;

    cout<<isCir(list)<<endl;
    return 0;
}

int ListInit(LinkList *L)
{
    (*L) = (LinkList)malloc(sizeof(Node));
    if(NULL == (*L))
    {
        return FAILURE;
    }
    (*L)->next = NULL;

    return SUCCESS;
}

int ListInsert(LinkList *L,int i,ElemType e)
{
    LinkList p = *L;
    int j = 1;
    while( p != NULL && j < i)
    {
        p = p->next;
        j++;
    }
    if( p == NULL || j > i)
    {
        return FAILURE;
    }
    LinkList n = (LinkList)malloc(sizeof(Node));
    if(NULL == n)
    {
        return FAILURE;
    }
    n->data = e;
    n->next = p->next;
    p->next = n;
    return SUCCESS;
}

ElemType visit(ElemType e)
{
    printf("%d ",e);
    return e;
}

int ListTraverse(LinkList L,ElemType(*print)(ElemType))
{
    if(NULL == L)
    {
        return FAILURE;
    }
    LinkList p = L->next;
    while(p)
    {
        p->data=print(p->data);
        p = p->next;
    }
    return SUCCESS;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章