链表

1.链表

顺序表的构建需要预先知道数据大小来申请连续的存储空间,而在进行空充时又需要进行数据的搬迁,所以使用起来并不是很灵活。
在这里插入图片描述

链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。
在这里插入图片描述

链表(Linked List)是一种常见的基础数据结构,是一只种类线性表,但是不像顺序表一样连续存储数据,而是在每一个节点(数据存储单元)里存放下一个节点的位置信息(即地址)。
在这里插入图片描述
2.单链表
单向链表也叫单链表,每个节点包含两个域,一个信息域(元素域)和一个链接域。这个链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值。
在这里插入图片描述

表元素域elem用来存放具体的数据。
链接域next用来存放下一个节点的位置(python中的标识)
变量p指向链表的头节点(首节点)的位置,从p出发能找到表中的任意节点。

单链表的节点可以单独写个类来存,实例化出结点

class SingleNode(object):
    """单链表的节点"""
    def __init__(self,item):
        #_item存放数据元素
        self.item = item
        #_next是下一个节点的标识
        self.next = None

然后再写一个类来实例化单链表,这个类封装单链表,里面写了如下函数实现功能

在这里插入图片描述
下面就来具体写一下里面的函数:
1.单链表的头部添加元素与尾部添加元素

在这里插入图片描述
头部添加元素:把新实例化的结点的next值置为原来链表的头(指向原来链表的头),再把head指向这个新结点;
尾部添加元素:原来链表尾结点的next为None,现在把原来尾部结点的next置为新结点(也就是指向新结点);

  def add(self,item):
        """头部添加元素"""
       #先创建一个保存item值的节点
       node  = SingleNode(item)
       #将新节点的链接域next指向头节点,即__head指向的位置
       node.next = self.__head
       #将链表的头__head指向新节点
       self.__head = node

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

2.指定位置添加元素
在这里插入图片描述
指定位置添加元素:找到指定位置,比如说要插入到第三个结点,则要找第二个结点,把新结点的next置为原来的第三个结点,也就是第二个结点的next值:newnode.next=oldnode.next,然后把第二个结点的next置为要插入的结点。

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

3.删除结点
在这里插入图片描述
删除头结点:原来的链表头指向要删除的头,现在只要把头(head)指向它的下一个结点就好了。
删除尾结点:只要把尾结点之前的那个结点的next置为None就好了。
删除中间结点:把要删除结点的前一个结点的next置为要删除结点的后一个结点(前一个结点跳过要删除的结点直接指向下下一个结点)。
注意:在c语言中要删除结点,不仅要做以上工作,还要将删除的结点释放(free),但在python中因为他的垃圾回收机制就不需要这样了,它会自动释放。

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

4.链表长度
求链表长度:依次遍历链表,每循环一次长度加1,直到到达链表尾部;

  def __len__(self):
        """
        链表长度:
            1. 如果当前链表为空, 直接返回0;
            1. 如果当前链表不为空, 依次遍历链表的每一个元素,计算长度
        """
        if self.is_empty():  #这里调用了判断链表是否为空函数
            return 0
        else:
            cur = self.head
            length = 0
            while cur != None:
                length += 1
                cur = cur.next
            return length

5.遍历整个链表
遍历整个链表:和求链表长度非常像,求长度是每循环一次长度加1,遍历是每循环一次就打印出结点元素

def trvel(self):
    """遍历链表"""
    if not self.is_empty():
        cur = self.head
        while cur.next != None:
            print(cur.element, end=',')
            cur = cur.next
        print(cur.element)
    else:
        print("空链表")

6.链表是否为空
判断链表是否为空:直接看链表的头结点是否为空,如果为空,链表就为空,如果不为空,链表就不为空。

 def is_empty(self):
        """判断链表是否为空"""
        return self.head == None

7.查找结点是否存在
查找结点是否存在:也是一次遍历,如果有结点的item值与传进来的值相等就返回True,如果到最后还没有找到就返回Flase;

整个单链表封装代码:

"""
单链表的封装
"""
class Node(object):
    """
    单链表节点的封装
    """

    def __init__(self, element):
        self.element = element
        self.next = None

class SingleLink(object):
    """
    单链表的封装
    """
    def __init__(self):
        # 默认情况下链表为空, 没有任何元素
        self.head = None

    def is_empty(self):
        """判断链表是否为空"""
        return self.head == None

    def __len__(self):
        """
        链表长度:
            1. 如果当前链表为空, 直接返回0;
            1. 如果当前链表不为空, 依次遍历链表的每一个元素,计算长度
        """
        if self.is_empty():
            return 0
        else:
            cur = self.head
            length = 0
            while cur != None:
                length += 1
                cur = cur.next
            return length

    def trvel(self):
        """遍历链表"""
        if not self.is_empty():
            cur = self.head
            while cur.next != None:
                print(cur.element, end=',')
                cur = cur.next
            print(cur.element)
        else:
            print("空链表")

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

    def add(self, item):
        """
        头部添加元素
            1. 先创建一个保存item值的节点
            2. 将新节点的链接域next指向头节点,即head指向的位置
            3. 将链表的头head指向新节点
        """
        node = Node(item)
        node.next = self.head
        self.head = node

    def insert(self, index, item):
        """
        指定位置添加元素
            1. 若指定位置index为第一个元素之前,则执行头部插入
            2. 若指定位置超过链表尾部,则执行尾部插入
            3. 否则, 找到指定位置
        """
        if index <= 0:
            self.add(item)
        elif index >= len(self):
            self.append(item)
        else:
            node = Node(item)
            count = 0  # 当前位置
            cur = self.head
            while count < index - 1:
                count += 1
                cur = cur.next
            node.next = cur.next
            cur.next = node

    def remove(self, item):
        """
        删除指定元素的节点:
         1 2 3 4 5
         1. 如果删除的是头结点, 指针直接指向头结点的下一个节点;
         2. 如果删除的不是头结点, 一直循环, 知道找到要删除的节点元素;
        """
        pre = None
        cur = self.head
        if cur.element == item:
            self.head = self.head.next
        else:
            while cur:
                if cur.element != item:
                    pre = cur
                    cur = cur.next
                else:
                    pre.next = pre.next.next
                    break



    def search(self, item):
        """
        判断查找的元素在节点中是否存在, 返回Bool类型
        """
        pass

if __name__ == '__main__':
    # 实例化单链表对象
    link = SingleLink()
    # 长度获取
    print("链表长度: ", len(link))
    # 遍历链表
    link.trvel()
    print("链表是否为空? ", link.is_empty())

    print("添加元素:")
    link.append(1)
    link.append(2)
    link.add(3)
    link.insert(1, 'hello')
    # 3 'hello' 1 2

    # 长度获取
    print("链表长度: ", len(link))
    # 遍历链表
    link.trvel()
    print("链表是否为空? ", link.is_empty())
    print("删除元素")
    link.remove(1)
    link.trvel()

3.单向循环链表

只要把单链表尾结点的next指向头就变循环了。
在这里插入图片描述
这里写一下查找结点是否存在:

 def search(self, item):
        """查找节点是否存在"""
        if self.is_empty():
            return False
        cur = self.__head
        if cur.item == item:
            return True
        while cur.next != self.__head:
            cur = cur.next
            if cur.item == item:
                return True
        return False

完整代码在单向循环链表里有写

4.双向链表

每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。
在这里插入图片描述
插入结点
头部插入:
在这里插入图片描述
中间插入:
在这里插入图片描述
尾部插入:
在这里插入图片描述
删除结点:
在这里插入图片描述

完整双向链表封装代码:

"""
双向链表的封装
"""


class Node(object):
    """
    双向链表节点的封装
    """

def __init__(self, element):
    self.element = element  # 数据域
    # 指针域
    self.next = None  # 指向后继节点的指针
    self.prev = None  # 指向前驱节点的指针

def __str__(self):
    return self.element


class DuLinkList(object):
    """
    双向链表的封装
    """

def __init__(self):
    self.head = None

def is_empty(self):
    """判断双向链表是否为空"""
    return self.head == None

def __len__(self):
    """获取双向链表的长度"""
    if self.is_empty():
        return 0
    cur = self.head
    linkLen = 0
    while cur:
        cur = cur.next
        linkLen += 1
    return linkLen

def travel(self):
    """遍历链表元素"""
    if not self.is_empty():
        cur = self.head
        while cur.next != None:
            print(cur.element, end=',')
            cur = cur.next
        print(cur.element)
    else:
        print("空链表")

def add(self, item):
    """
    头部添加元素
        1. 先创建一个保存item值的节点
        2. 将新节点的链接域next指向头节点,即head指向的位置
        3. 将链表的头head指向新节点
    """
    node = Node(item)
    if self.is_empty():
        self.head = node
    else:
        node.next = self.head
        self.head.prev = node
        self.head = node

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

def insert(self, index, item):
    """
    指定位置添加元素
        1. 若指定位置index为第一个元素之前,则执行头部插入
        2. 若指定位置超过链表尾部,则执行尾部插入
        3. 否则, 找到指定位置
    """
    if index <= 0:
        self.add(item)
    elif index >= len(self):
        self.append(item)
    else:
        node = Node(item)
        count = 0  # 当前位置
        cur = self.head
        while count < index - 1:
            count += 1
            cur = cur.next
        node.next = cur.next
        cur.next = node
        node.prev = cur
        cur.next.prev = node

def remove(self, item):
    """
    删除指定元素的节点:
     1 2 3 4 5
     1. 如果删除的是头结点, 指针直接指向头结点的下一个节点;
     2. 如果删除的不是头结点, 一直循环, 知道找到要删除的节点元素;
    """
    if self.is_empty():
        return
    pre = None
    cur = self.head
    # 如果删除的是头结点, 指针直接指向头结点的下一个节点;
    if cur.element == item:
        self.head = self.head.next
    else:
        while cur:
            if cur.element != item:
                pre = cur
                cur = cur.next
            else:
                # 判断删除的是否为尾部节点, 如果是, 则直接让pre.next指向为None;
                if not cur.next:
                    pre.next = None
                    break

                else:
                    # pre.next = pre.next.next
                    pre.next = cur.next
                    cur.next.prev = pre
                    break


def search(self, item):
    cur = self.head
    while cur:
        if cur.element == item:
            return  True
        cur = cur.next
    else:
        return  False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值