PHP 判斷鍊錶是否相交

2021-09-06 06:16:43 字數 3392 閱讀 9662

解題思路:

分三種情況

1.兩個鍊錶都是無環鏈表,則使用指標p1,p2,分別遍歷到兩個鍊錶尾,如果p1===p2,說明鍊錶相交,否則不相交

2.兩個鍊錶有乙個有環,另乙個無環,那麼這種情況鍊錶肯定不相交,因為如果其中乙個有環,另乙個和它相交,另乙個也肯定會有環

3.兩個鍊錶都有環,找到鍊錶a和鍊錶b的環中的兩個節點p1,p2,用pa=p1,然後用pa=pa->next,直到pa===p1(意思是讓pa在環內跑一圈),如果在跑的過程中發現pa === p2,說明兩個鍊錶的環是同乙個,則相交,如果到達pa===p1,說明兩個鍊錶不相交

下面是**

1

<?php2#

判斷鍊錶是否相交3#

一共有三種情況4#

1.兩個鍊錶都是無環鏈表5#

2.乙個是有環鏈表,另乙個是無環鏈表,這種情況不可能相交6#

3.兩個鍊錶都是有環鏈表78

class

node

1213

#判斷是否有環

14function test_circle($head

) 26}27

28#鍊錶無環

29return

null;30

}3132#

判斷兩個無環鏈表是否相交

33function test_intersect_******($head1, $head2

) 40

41while ($p2->next != null

) 4445#

如果兩個鍊錶相交,則他們末必然相等46#

此處要注意用三等號,因為要判斷引用是否相同

47return

$p1 === $p2 ? true : false;48

}4950#

判斷兩個鍊錶是否相交

51function test_intersect($head1, $head2

) 5960#

如果其中乙個鍊錶存在環另乙個不存在環,則肯定不會相交

61if (($cir1 != null && $cir2 == null) || ($cir1 == null && $cir2 != null

)) 6465#

兩個鍊錶都存在環,如果相交,則兩個鍊錶的環肯定是同乙個66#

利用cir1在環內走一圈,如果沒有遇到cir2,說明兩個鍊錶不相交

67$p = $cir1;68

while ($cir1 !== $cir2

) 73}74

return

true;75

}7677#

head1,head2無環且相交

78$head1 = new

node();

79$head2 = new

node();

80$n11 = new

node();

81$n12 = new

node();

82$n21 = new

node();

83$n22 = new

node();

84$n23 = new

node();

85$np1 = new

node();

86$np2 = new

node();

87$head1->next = $n11;88

$n11->next = $n12;89

$n12->next = $np1;90

$np1->next = $np2;91

$head2->next = $n21;92

$n21->next = $n22;93

$n22->next = $n23;94

$n23->next = $np1;95

96$t = test_intersect($head1, $head2

);97

var_dump($t

);98

echo "

";99

100#

head1,head2其中乙個有環

101$head1 = new

node();

102$head2 = new

node();

103$n11 = new

node();

104$n12 = new

node();

105$n21 = new

node();

106$n22 = new

node();

107$n23 = new

node();

108$head1->next = $n11

;109

$n11->next = $n12

;110

$n12->next = $head1

;111

$head2->next = $n21

;112

$n21->next = $n22

;113

$n22->next = $n23

;114

115$t = test_intersect($head1, $head2

);116

var_dump($t

);117

echo "

";118

119#

head1,head2都有環且相交

120$head1 = new

node();

121$head2 = new

node();

122$n11 = new

node();

123$n12 = new

node();

124$n21 = new

node();

125$n22 = new

node();

126$n23 = new

node();

127$head1->next = $n11

;128

$n11->next = $n12

;129

$n12->next = $head1

;130

$head2->next = $n21

;131

$n21->next = $n22

;132

$n22->next = $n23

;133

$n23->next = $n12

;134

135$t = test_intersect($head1, $head2

);136

var_dump($t

);137

echo "

";138 ?>

bool(true) 

bool(false) 

bool(true)

判斷倆鍊錶是否相交

給出倆個單向鍊錶的頭指標,比如h1,h2,判斷這倆個鍊錶是否相交。為了簡化問題,我們假設倆個鍊錶均不帶環。問題擴充套件 1.如果鍊錶可能有環列?2.如果需要求出倆個鍊錶相交的第乙個節點列?建立hash表 由於節點位址指標就是乙個整型,假設鍊錶都是在堆中動態建立的,可以使用堆的起始位址作為偏移量,以位...

判斷倆鍊錶是否相交

給出倆個單向鍊錶的頭指標,比如h1,h2,判斷這倆個鍊錶是否相交。為了簡化問題,我們假設倆個鍊錶均不帶環。問題擴充套件 1.如果鍊錶可能有環列?2.如果需要求出倆個鍊錶相交的第乙個節點列?建立hash表 由於節點位址指標就是乙個整型,假設鍊錶都是在堆中動態建立的,可以使用堆的起始位址作為偏移量,以位...

判斷兩鍊錶是否相交

1.判斷鍊錶帶不帶環 2.如果都不帶環,就判斷尾節點是否相等 3.如果都帶環,判斷一條鍊錶上兩指標相遇的那個節點,在不在另一條鍊錶上,如果在,則相交,如果不在,則不相交 那麼如何判斷是否帶環?設定兩個指標 p1 p2 開始都指向鍊錶的頭,p2 每次移動兩步 p1每次移動一步,如果存在環,則他們必在環...