結構之美:判斷單鏈表中是否有環

在編程之美上看到這個題,判斷一個單鏈表中是不是有環,網上也看到了很不錯的解法和分析,還有完整的代碼,轉載過來,共同學習:

轉載地址:http://www.nowamagic.net/librarys/veda/detail/1837

-----------------------------------------------------------------------------------------------------------------------------------------------------

有環的定義是,鏈表的尾節點指向了鏈接中間的某個節點。比如下圖,如果單鏈表有環,則在遍歷時,在通過6之後,會重新回到3,那麼我們可以在遍歷時使用兩個指針,看兩個指針是否相等。

方法一:使用p、q兩個指針,p總是向前走,但q每次都從頭開始走,對於每個節點,看p走的步數是否和q一樣。如圖,當p從6走到3時,用了6步,此時若q從head出發,則只需兩步就到3,因而步數不等,出現矛盾,存在環。

方法二:使用p、q兩個指針,p每次向前走一步,q每次向前走兩步,若在某個時候p == q,則存在

對於方法一,其實現代碼爲:

//if two pointer are equal, but they don't have the same steps, then has a loop
int HasLoop(LinkList L)
{
    LinkList cur1 = L;  // 定義結點 cur1
    int pos1 = 0;       // cur1 的步數
    while(cur1){        // cur1 結點存在
        LinkList cur2 = L;  // 定義結點 cur2
        int pos2 = 0;       // cur2 的步數
        pos1 ++;            // cur1 步數自增
        while(cur2){        // cur2 結點不爲空
            pos2 ++;        // cur2 步數自增
            if(cur2 == cur1){   // 當cur1與cur2到達相同結點時
                if(pos1 == pos2)    // 走過的步數一樣
                    break;          // 說明沒有還
                else                // 否則
                    return 1;       // 有環並返回1
            }
            cur2 = cur2->next;      //  如果沒發現環,繼續下一個結點
        }
        cur1 = cur1->next;  // cur1繼續向後一個結點
    }
    return 0;
}

方法二則比較簡單,就不註釋了。

//using step1 and step2 here
//if exists a loop, then the pointer which use step2 will catch up with the pointer which uses step1
int HasLoop2(LinkList L)
{
    int step1 = 1;
    int step2 = 2;
    LinkList p = L;
    LinkList q = L;
    //while (p != NULL && q != NULL && q->next == NULL)
    while (p != NULL && q != NULL && q->next != NULL)
    {
        p = p->next;
        if (q->next != NULL)
            q = q->next->next;
        printf("p:%d, q:%d \n", p->data, q->data);
        if (p == q)
            return 1;
    }
    return 0;
}

完整的可運行的程序:

#include "stdio.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;/* Status是函數的類型,其值是函數結果狀態代碼,如OK等 */
typedef int ElemType;/* ElemType類型根據實際情況而定,這裏假設爲int */

typedef struct Node
{
    ElemType data;
    struct Node *next;
}Node;
typedef struct Node *LinkList; /* 定義LinkList */

Status visit(ElemType c)
{
    printf("%d ",c);
    return OK;
}

/* 初始化順序線性表 */
Status InitList(LinkList *L)
{
    *L=(LinkList)malloc(sizeof(Node)); /* 產生頭結點,並使L指向此頭結點 */
    if(!(*L)) /* 存儲分配失敗 */
            return ERROR;
    (*L)->next=NULL; /* 指針域爲空 */

    return OK;
}

/* 初始條件:順序線性表L已存在。操作結果:返回L中數據元素個數 */
int ListLength(LinkList L)
{
    int i=0;
    LinkList p=L->next; /* p指向第一個結點 */
    while(p)
    {
        i++;
        p=p->next;
    }
    return i;
}

/* 初始條件:順序線性表L已存在 */
/* 操作結果:依次對L的每個數據元素輸出 */
Status ListTraverse(LinkList L)
{
    LinkList p=L->next;
    while(p)
    {
        visit(p->data);
        p=p->next;
    }
    printf("\n");
    return OK;
}

/*  隨機產生n個元素的值,建立帶表頭結點的單鏈線性表L(頭插法) */
void CreateListHead(LinkList *L, int n)
{
	LinkList p;
	int i;
	srand(time(0));                         /* 初始化隨機數種子 */
	*L = (LinkList)malloc(sizeof(Node));
	(*L)->next = NULL;                      /*  先建立一個帶頭結點的單鏈表 */
	for (i=0; i < n; i++)
	{
		p = (LinkList)malloc(sizeof(Node)); /*  生成新結點 */
		p->data = rand()%100+1;             /*  隨機生成100以內的數字 */
		p->next = (*L)->next;
		(*L)->next = p;						/*  插入到表頭 */
	}
}

/*  隨機產生n個元素的值,建立帶表頭結點的單鏈線性表L(尾插法) */
void CreateListTail(LinkList *L, int n)
{
	LinkList p,r;
	int i;
	srand(time(0));                      /* 初始化隨機數種子 */
	*L = (LinkList)malloc(sizeof(Node)); /* L爲整個線性表 */
	r=*L;                                /* r爲指向尾部的結點 */
	for (i=0; i < n; i++)
	{
		p = (Node *)malloc(sizeof(Node)); /*  生成新結點 */
		p->data = rand()%100+1;           /*  隨機生成100以內的數字 */
		r->next=p;                        /* 將表尾終端結點的指針指向新結點 */
		r = p;                            /* 將當前的新結點定義爲表尾終端結點 */
	}
	r->next = NULL;                       /* 表示當前鏈表結束 */
	// 創建有環鏈表
    //r->next = p;
}

/* 初始條件:順序線性表L已存在,1≤i≤ListLength(L) */
/* 操作結果:刪除L的第i個數據元素,並用e返回其值,L的長度減1 */
Status ListDelete(LinkList *L,int i,ElemType *e)
{
	int j;
	LinkList p,q;
	p = *L;
	j = 1;
	while (p->next && j < i)	/* 遍歷尋找第i個元素 */
	{
        p = p->next;
        ++j;
	}
	if (!(p->next) || j > i)
	    return ERROR;           /* 第i個元素不存在 */
	q = p->next;
	p->next = q->next;			/* 將q的後繼賦值給p的後繼 */
	*e = q->data;               /* 將q結點中的數據給e */
	free(q);                    /* 讓系統回收此結點,釋放內存 */
	return OK;
}

int HasLoop(LinkList L)
{
    LinkList cur1 = L;  // 定義結點 cur1
    int pos1 = 0;       // cur1 的步數
    while(cur1){        // cur1 結點存在
        LinkList cur2 = L;  // 定義結點 cur2
        int pos2 = 0;       // cur2 的步數
        pos1 ++;            // cur1 步數自增
        while(cur2){        // cur2 結點不爲空
            pos2 ++;        // cur2 步數自增
            if(cur2 == cur1){   // 當cur1與cur2到達相同結點時
                if(pos1 == pos2)    // 走過的步數一樣
                    break;          // 說明沒有還
                else                // 否則
                    return 1;       // 有環並返回1
            }
            cur2 = cur2->next;      //  如果沒發現環,繼續下一個結點
        }
        cur1 = cur1->next;  // cur1繼續向後一個結點
    }
    return 0;
}

//using step1 and step2 here
//if exists a loop, then the pointer which use step2 will catch up with the pointer which uses step1
int HasLoop2(LinkList L)
{
    int step1 = 1;
    int step2 = 2;
    LinkList p = L;
    LinkList q = L;
    //while (p != NULL && q != NULL && q->next == NULL)
    while (p != NULL && q != NULL && q->next != NULL)
    {
        p = p->next;
        if (q->next != NULL)
            q = q->next->next;
        printf("p:%d, q:%d \n", p->data, q->data);
        if (p == q)
            return 1;
    }
    return 0;
}

int main()
{
    LinkList L;
    Status i;
    char opp;
    ElemType e;
    int find;
    int tmp;

    i=InitList(&L);
    printf("初始化L後:ListLength(L)=%d\n",ListLength(L));

    printf("\n1.查看鏈表 \n2.創建鏈表(尾插法) \n3.鏈表長度 \n4.判斷鏈表是否有環 \n0.退出 \n請選擇你的操作:\n");
    while(opp != '0'){
        scanf("%c",&opp);
        switch(opp){
            case '1':
                ListTraverse(L);
                printf("\n");
                break;

            case '2':
                CreateListTail(&L,20);
                printf("整體創建L的元素(尾插法):\n");
                ListTraverse(L);
                printf("\n");
                break;

            case '3':
                //clearList(pHead);   //清空鏈表
                printf("ListLength(L)=%d \n",ListLength(L));
                printf("\n");
                break;

            case '4':
                //find = HasLoop(L);
                if( HasLoop(L) )
                {
                    printf("方法一: 鏈表有環\n");
                }
                else
                {
                    printf("方法一: 鏈表無環\n");
                }

                if( HasLoop2(L) )
                {
                    printf("方法二: 鏈表有環\n");
                }
                else
                {
                    printf("方法二: 鏈表無環\n");
                }
                ListTraverse(L);
                printf("\n");
                break;

            case '0':
                exit(0);
        }
    }

}



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