1 next;15 }16 17 $j = 1;18 $cnode = $head;19 while ($j < $n - $i) {20 $j++;21 $cnode = $cnode->next;22 }23 24 return $cnode;25 }26 27 #第二种方法,使用两个指针同时移动28 function last_i_2($head, $i) {29 $p1 = $head;30 $p2 = $head;31 $k = 0;32 33 while ($k < $i) {34 $p1 = $p1->next;35 $k++;36 }37 38 while (($p1 = $p1->next) != null) {39 $p2 = $p2->next;40 }41 42 return $p2;43 }44 45 $head = new Node();46 $n1 = new Node();47 $n2 = new Node();48 $n3 = new Node();49 $n4 = new Node();50 $head->data = 0;51 $n1->data = 1;52 $n2->data = 2;53 $n3->data = 3;54 $n4->data = 4;55 $head->next = $n1;56 $n1->next = $n2;57 $n2->next = $n3;58 $n3->next = $n4;59 60 echo last_i($head, 2)->data . "";61 echo last_i_2($head, 2)->data;62 ?>
2
2