双向链表

Testing Is Documentation

tests/Stack/LinkedListTest.php双向链表 - 图1

在 PHP 双向链表的基础上加上数据类型验证功能,不少业务场景中保证链表中数据一致性。

阻止链表返回空数据时抛出异常的默认行为。

底层基于 spldoublylinkedlist 开发,相关文档 http://php.net/manual/zh/class.spldoublylinkedlist.php双向链表 - 图2

Uses

  1. <?php
  2. use Leevel\Stack\LinkedList;

链表基本使用方法

  1. public function testBaseUse(): void
  2. {
  3. $linkedList = new LinkedList();
  4. $this->assertSame(0, $linkedList->count());
  5. $this->assertNull($linkedList->pop());
  6. $this->assertNull($linkedList->pop());
  7. }

push 链表尾部弹出元素

  1. public function testPush(): void
  2. {
  3. $linkedList = new LinkedList();
  4. $linkedList->push(5);
  5. $linkedList->push(6);
  6. $this->assertSame(2, $linkedList->count());
  7. $this->assertSame(6, $linkedList->pop());
  8. $this->assertSame(5, $linkedList->pop());
  9. $this->assertSame(0, $linkedList->count());
  10. }

unshift 链表头插入元素

  1. public function testUnshift(): void
  2. {
  3. $linkedList = new LinkedList();
  4. $linkedList->unshift(5);
  5. $linkedList->unshift(6);
  6. $this->assertSame(2, $linkedList->count());
  7. $this->assertSame(5, $linkedList->pop());
  8. $this->assertSame(6, $linkedList->pop());
  9. $this->assertSame(0, $linkedList->count());
  10. }

add 链表指定位置插入新值

  1. public function testAdd(): void
  2. {
  3. $linkedList = new LinkedList();
  4. $linkedList->add(0, 'hello');
  5. $linkedList->add(1, 'world');
  6. $linkedList->add(2, 'foo');
  7. $linkedList->add(3, 'bar');
  8. $this->assertSame('hello', $linkedList->offsetGet(0));
  9. $this->assertSame('world', $linkedList->offsetGet(1));
  10. $this->assertSame('foo', $linkedList->offsetGet(2));
  11. $this->assertSame('bar', $linkedList->offsetGet(3));
  12. }

offsetSet 更新链表指定位置链表的值

  1. public function testOffsetSet(): void
  2. {
  3. $linkedList = new LinkedList();
  4. $linkedList->add(0, 'hello');
  5. $linkedList->add(1, 'world');
  6. $linkedList->add(2, 'foo');
  7. $linkedList->add(3, 'bar');
  8. $linkedList->offsetSet(0, 'hello2');
  9. $linkedList->offsetSet(1, 'world2');
  10. $linkedList->offsetSet(2, 'foo2');
  11. $linkedList->offsetSet(3, 'bar2');
  12. $this->assertSame('hello2', $linkedList->offsetGet(0));
  13. $this->assertSame('world2', $linkedList->offsetGet(1));
  14. $this->assertSame('foo2', $linkedList->offsetGet(2));
  15. $this->assertSame('bar2', $linkedList->offsetGet(3));
  16. }

链表支持元素类型限定

  1. public function testValidateType(): void
  2. {
  3. $this->expectException(\InvalidArgumentException::class);
  4. $this->expectExceptionMessage('The linkedlist element type verification failed, and the allowed type is string.');
  5. $linkedList = new LinkedList(['string']);
  6. $linkedList->push(5);
  7. }