1. 程式人生 > >劍指offer——連結串列中環的入口結點

劍指offer——連結串列中環的入口結點

概述

題目描述
給一個連結串列,若其中包含環,請找出該連結串列的環的入口結點,否則,輸出null。

C++ AC程式碼

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};

class Solution {
    public:
        ListNode* EntryNodeOfLoop(ListNode*
pHead){ //連結串列為空則不存在環,返回NULL if(pHead == NULL){ return NULL; } ListNode* front = pHead; ListNode* rear = pHead->next; /*首尾指標進行遍歷,首指標每次走一步,尾指標走兩步 跳出迴圈,則存在環 */ while(front !=
rear && front != NULL && rear != NULL){ front = front->next; rear = rear->next; if(rear != NULL){ rear = rear->next; } } //計數器設定為1,是為了遍歷陣列時得到環的尾結點的後一個結點即頭結點 int cnt =
1; ListNode* tmp = rear->next; if(front == rear && front != NULL){ while(tmp != front){ cnt++; tmp = tmp->next; } }else{//不存在環則返回NULL return NULL; } ListNode* tmp1 = pHead; ListNode* tmp2 = pHead; //tmp1儲存環的頭結點 for(int i = 0 ; i < cnt ; i++){ tmp1 = tmp1->next; } while(tmp1 != tmp2){ tmp1 = tmp1->next; tmp2 = tmp2->next; } return tmp1; } };