文档详情

数据结构课后实验源代码.docx

发布:2023-12-05约2.26千字共4页下载文档
文本预览下载声明

数据结构课后实验源代码

数据结构是计算机科学中的一门重要课程,主要研究如何组织和处理数据。在学习数据结构时,经常会进行一些课后实验,以巩固所学的知识,并且进一步加深对数据结构的理解和应用。

以下是一份数据结构课后实验的源代码的相关参考内容,介绍了一个常见的数据结构——链表。

```python

#定义链表节点的类

classListNode:

def__init__(self,val=0,next=None):

self.val=val

self.next=next

#定义链表类

classLinkedList:

def__init__(self):

self.head=None

#在链表尾部插入一个新节点

defappend(self,val):

new_node=ListNode(val)

ifnotself.head:

self.head=new_node

else:

curr_node=self.head

whilecurr_node.next:

curr_node=curr_node.next

curr_node.next=new_node

#在链表头部插入一个新节点

defprepend(self,val):

new_node=ListNode(val)

ifnotself.head:

self.head=new_node

else:

new_node.next=self.head

self.head=new_node

#删除链表中第一个与给定值相等的节点

defdelete(self,val):

ifnotself.head:

returnNone

ifself.head.val==val:

self.head=self.head.next

return

curr_node=self.head

whilecurr_node.next:

ifcurr_node.next.val==val:

curr_node.next=curr_node.next.next

break

curr_node=curr_node.next

#打印链表的所有节点值

defprint_list(self):

curr_node=self.head

whilecurr_node:

print(curr_node.val,end=)

curr_node=curr_node.next

print()

#创建一个链表对象并进行测试

if__name__==__main__:

linked_list=LinkedList()

linked_list.append(1)

linked_list.append(2)

linked_list.append(3)

linked_list.prepend(0)

linked_list.print_list()

linked_list.delete(2)

linked_list.print_list()

```

上述代码是基于Python语言实现的链表数据结构,其中`ListNode`类表示链表的节点,每个节点包含一个值和指向下一个节点的指针。`LinkedList`类表示链表,拥有头节点的引用。

代码中提供了一些基本操作,如在链表尾部插入节点、在链表头部插入节点、删除链表中的某个值等。通过这些操作,可以实现链表的基本功能,如插入、删除和遍历。

在主程序中,创建一个链表对象`linked_list`,并进行一系列的操作测试。首先使用`append`方法在链表尾部插入节点1、2和3,然后使用`prepend`方法在链表头

显示全部
相似文档