python数据结构之链表

单链表

节点实现

```python
class Node(object):
    """节点"""
    def __init__(self, elem):
        self.elem = elem
        self.next = None
```

头部添加元素

```python
def add(self, item):
    """在头部添加元素"""
    node = Node(item)
    node.next = self.__head
    self.__head = node
```

尾部添加元素

```python
def append(self, item):
    """在尾部添加元素"""
    node = Node(item) 
    # 先判断链表是否为空,若是空链表,则将_head指向新节点
    if self.is_empty():
        self.__head = node
    # 若不为空,则找到尾部,将尾节点的next指向新节点
    else:
        cur = self.__head
        while cur.next != None:
            cur = cur.next
        cur.next = node
 ```

指定位置添加元素

```python
def insert(self, pos, item):
    """在指定位置添加元素"""
    node = Node(item)
    # 若指定位置pos为第一个元素之前,则执行头部插入
    if pos <= 0:
        self.add(item)
    # 若指定位置超过链表尾部,则执行尾部插入
    elif pos > (self.length()-1):
        self.append(item)
    # 找到指定位置
    else:
        pre = self.__head
        count = 0
        # pre用来指向指定位置pos的前一个位置pos-1,初始从头节点开始移动到指定位置
        while count < (pos-1):
            count += 1
            pre = pre.next
        # 先将新节点node的next指向插入位置的节点
        node.next = pre.next
        # 将插入位置的前一个节点的next指向新节点
        pre.next = node
 ```

删除节点

 ```python
 def remove(self, item):
        """删除节点"""
        cur = self.__head
        pre = None
        while cur != None:
            # 找到了指定元素
            if cur.elem == item:
                # 如果第一个就是删除的节点
                if cur == self.__head:
                    # 将头指针指向头节点的后一个节点
                    self.__head = cur.next
                else:
                    # 将删除位置前一个节点的next指向删除位置的后一个节点
                    pre.next = cur.next
                break
            else:
                # 继续按链表后移节点
                pre = cur
                cur = cur.next
  ```

查找节点是否存在

 ```python
 def search(self, item):
        """查找节点"""
        cur = self.__head
        while cur != None:
            if cur.elem == item:
                return True
            else:
                cur = cur.next
        return False
  ```

判断是否为空

```python
def is_empty(self):
    """判断是否为空"""
    return self.__head == None
```

求链表长度

```python
def length(self):
    """链表长度"""
    # cur用来移动遍历节点
    cur = self.__head
    # count记录数量
    count = 0
    while cur != None:
        count += 1
        cur = cur.next
    return count
```

遍历

```python
def travel(self):
    """遍历"""
    cur = self.__head
    while cur != None:
        print(cur.elem,end=" ")
        cur = cur.next
```

完整代码

更多内容请见

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值