Skip to content

Commit

Permalink
Add 005
Browse files Browse the repository at this point in the history
  • Loading branch information
tobegit3hub committed Apr 2, 2016
1 parent 6f5d7c7 commit 41fb977
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions 005链表.md
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)

0 comments on commit 41fb977

Please sign in to comment.