-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoddEvenLinkedList.php
More file actions
68 lines (48 loc) · 1.1 KB
/
oddEvenLinkedList.php
File metadata and controls
68 lines (48 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* @param ListNode $head
* @return ListNode
*/
function oddEvenList($head) {
if($head === null){
return null;
}
$cur = $head;
//当前位置计数
$i = 0;
//奇数位置链表
$oddhead = new ListNode();
$oddtail = $oddhead;
//偶数位置链表
$evenhead = new ListNode();
$eventail = $evenhead;
while ($cur !== null){
//当前位置计数
$i++;
//下一节点预报存
$tmp = $cur->next;
//判断位置奇数偶数
$is_odd = ($i % 2) ? true : false;
$cur->next = null;
//奇数位置放置于奇数列
if($is_odd){
$oddtail->next = $cur;
$oddtail = $cur;
}else{
$eventail->next = $cur;
$eventail = $cur;
}
//移动指针
$cur = $tmp;
}
$oddtail->next = $evenhead->next;
return $oddhead->next;
}