forked from tobegit3hub/tobe-algorithm-manual
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6f5d7c7
commit 41fb977
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
|
||
# 实现链表数据结构 | ||
|
||
## 什么是链表 | ||
|
||
链表是常用的数据机构之一,其种类也非常多,包括单向链表、双向链表等。这里会使用Python实现简单或通用的链表数据结构。 | ||
|
||
## 如何实现单向链表 | ||
|
||
首先是定义链表的Node,我们设计链表除了自己的数据外,还包含一个next对象。 | ||
|
||
``` | ||
class Node(object): | ||
def __init__(self, data, next=None): | ||
self.data = data | ||
self.next = next | ||
node = Node("node1") | ||
``` | ||
|
||
然后我们就可以实现List类,主要是包含head的节点,顺便实现遍历的方法。 | ||
|
||
``` | ||
class List(object): | ||
def __init__(self, head=None): | ||
self.head = head | ||
def add_node(self, node, data): | ||
if node != None: | ||
new_node = Node(data) | ||
node.next = new_node | ||
return new_node | ||
def travel(self, node): | ||
if node != None: | ||
print(node.data) | ||
if node.next != None: | ||
self.travel(node.next) | ||
head = Node("node1") | ||
list = List(head) | ||
node2 = list.add_node(head, "node2") | ||
node3 = list.add_node(node2, "node3") | ||
list.travel(head) | ||
``` | ||
|
||
|
||
这是本章内容,希望对你有所帮助。[进入下一章](./006栈.md) |