数据结构与算法之数据结构 链表插入 头插法 / 尾插法

数据结构与算法阿木 发布于 2025-07-11 7 次阅读


摘要:

链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表的插入操作是链表操作中最为基础和重要的部分。本文将详细介绍链表插入操作中的两种常见方法:头插法和尾插法,并通过代码示例进行深入解析。

一、

链表是一种线性数据结构,与数组相比,链表具有动态分配内存、插入和删除操作方便等优点。在链表中,每个节点包含数据和指向下一个节点的指针。插入操作是链表操作中最为常见和基础的操作之一,本文将重点介绍头插法和尾插法两种插入方法。

二、链表的基本概念

1. 节点结构

链表中的每个节点包含两部分:数据和指针。数据部分存储实际的数据值,指针部分存储指向下一个节点的地址。

python

class Node:


def __init__(self, data):


self.data = data


self.next = None


2. 链表结构

链表由一系列节点组成,每个节点通过指针连接。链表的头节点是链表的起点,尾节点的指针为None。

python

class LinkedList:


def __init__(self):


self.head = None


三、头插法

头插法是指在链表头部插入新节点的方法。以下是头插法的实现步骤:

1. 创建新节点,并赋值数据。

2. 将新节点的指针指向原链表的头部。

3. 将原链表的头部指向新节点。

python

def insert_at_head(self, data):


new_node = Node(data)


new_node.next = self.head


self.head = new_node


四、尾插法

尾插法是指在链表尾部插入新节点的方法。以下是尾插法的实现步骤:

1. 创建新节点,并赋值数据。

2. 遍历链表,找到尾节点。

3. 将尾节点的指针指向新节点。

python

def insert_at_tail(self, data):


new_node = Node(data)


if self.head is None:


self.head = new_node


return


current = self.head


while current.next:


current = current.next


current.next = new_node


五、代码示例

以下是一个完整的链表插入操作的代码示例,包括头插法和尾插法:

python

class Node:


def __init__(self, data):


self.data = data


self.next = None

class LinkedList:


def __init__(self):


self.head = None

def insert_at_head(self, data):


new_node = Node(data)


new_node.next = self.head


self.head = new_node

def insert_at_tail(self, data):


new_node = Node(data)


if self.head is None:


self.head = new_node


return


current = self.head


while current.next:


current = current.next


current.next = new_node

def display(self):


current = self.head


while current:


print(current.data, end=' ')


current = current.next


print()

创建链表并插入节点


linked_list = LinkedList()


linked_list.insert_at_head(10)


linked_list.insert_at_head(20)


linked_list.insert_at_tail(30)


linked_list.insert_at_tail(40)

打印链表


linked_list.display()


六、总结

本文详细介绍了链表插入操作中的头插法和尾插法。通过代码示例,读者可以了解到这两种方法的实现步骤和细节。在实际应用中,根据具体需求选择合适的插入方法,可以提高链表操作的效率。