在C/C++中,通常采用“指针+结构体”来实现链表;而在Python中,则可以采用“引用+类”来实现链表。

节点类:

class Node:
def __init__(self, data):
self.data = data
self.next = None

链表类:

class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
link_list = LinkedList()
def is_empty(self):
return self.head is None
def append(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail =node
def iter(self):
if not iter.head:
return
cur = self.head
   yield cur.data
while cur.next:
cur = cur.next
yield cur.data
#先判断是不是空链表,yield head.data 再用while循环遍历

链表的头结点head 和 尾节点tail 都属于node.

insert:先将要插入的节点的next指向之后链表的head,然后将之前链表的next指向 将要插入的节点。

def insert(self, idx, value):
cur = self.head
cur_idx = 0
if cur is None:
raise Exception('That list is and empty list!')
while cur_idx < idx-1:
cur = cur.next
if cur is None:
raise Exception('List length less than index!')
cur_idx += 1
node = Node(value)
node.next = cur.next
cur.next = node
if node.next is None:
self.tail = node
def remove(self, idx):
cur = self.head
cur_idx = 0
#空指针
if self.head = None:
raise Exception('This is an empty list')
while cur_idx < idx-1:
cur = cur.next
#给出的索引大于链表的长度
if cur is None:
raise Exception('list length less than index')
cur_idx +=1
if idx == 0: #当删除第一个节点时
self.head = cur.next
cur = cur.next
return
if self.head is self.tail: #当只有一个节点时
self.head = None
self.tail = None
return
cur.next = cur.next.next
if cur.next is None: #当删除最后一个节点时
self.tail = cur
def size(self):
i = 0
cur = self.head
if current is None:
return 'The list is an empty list'
while cur.next is not None:
i +=1
cur = cur.next
return i
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.data == item:
found = True
else:
current = current.next
return found

单链表逆置

1,迭代

# -*- coding: utf-8 -*-
#!/bin/env python
# Python2.7 class Node(object):
def __init__(self):
self.value = None
self.next = None
def __str__(self):
return str(self.value) def reverse_list(head):
if not head or not head.next:
return head
pre = None
while head:
next = head.next # 缓存当前节点的向后指针,待下次迭代用
head.next = pre # 关键:把当前节点向前指针(pre)作为当前节点的向后指针
pre = head # 把当前指针赋值给 下次迭代 节点的 向前指针
head = next # 作为下次迭代时的(当前)节点
return pre # 返回头指针,头指针就是迭代最后一次的head(赋值给类pre) if __name__ == '__main__': three = Node()
three.value = 3 two = Node()
two.value = 2
two.next = three one = Node()
one.value = 1
one.next = two head = Node()
head.value = 0
head.next = one newhead = reverse_list(head)
while newhead:
print newhead.value
newhead = newhead.next

比较形象的图

2,递归

# 临界点:head.next为None
# 先递归到 把最后一个节点指向 newhead
# 然后一步步从后往前逆置 def reverse_recursion(head):
if not head or not head.next:
return head new_head = reverse_recursion(head.next) head.next.next = head
head.next = None
return new_head

python 链表的更多相关文章

  1. Python链表的实现与使用(单向链表与双向链表)

    参考[易百教程]用Python实现链表及其功能 """ python链表的基本操作:节点.链表.增删改查 """ import sys cl ...

  2. Python链表操作(实现)

    Python链表操作 在Python开发的面试中,我们经常会遇到关于链表操作的问题.链表作为一个非常经典的无序列表结构,也是一个开发工程师必须掌握的数据结构之一.在本文中,我将针对链表本身的数据结构特 ...

  3. python 链表表达式 map、filter易读版

    链表推导式 [x for x in x] 链表推导式提供了一个创建链表的简单途径,无需使用 map(), filter() 以及 lambda.返回链表的定义通常要比创建这些链表更清晰.每一个链表推导 ...

  4. Python链表与反链表

    # -*- coding:utf8 -*- #/usr/bin/env python class Node(object): def __init__(self, data, pnext = None ...

  5. python链表的实现

    根据Problem Solving with Algorithms and Data Structures using Python 一书用python实现链表 书籍在线网址http://intera ...

  6. python链表的实现,有注释

    class Node():                   #node实现,每个node分为两部分:一部分含有链表元素,成数据域;另一部分为指针,指向下一个  __slots__=['_item' ...

  7. python 链表的反转

    code #!/usr/bin/python # -*- coding: utf- -*- class ListNode: def __init__(self,x): self.val=x self. ...

  8. python 链表、堆、栈

    简介 很多开发在开发中并没有过多的关注数据结构,当然我也是,因此,我写这篇文章就是想要带大家了解一下这些分别是什么东西. 链表 概念:数据随机存储,并且通过指针表示数据之间的逻辑关系的存储结构. 链表 ...

  9. Add Two Numbers(from leetcode python 链表)

    给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(2 -& ...

随机推荐

  1. PAT 1064. 朋友数(20)

    如果两个整数各位数字的和是一样的,则被称为是“朋友数”,而那个公共的和就是它们的“朋友证号”.例如123和51就是朋友数,因为1+2+3 = 5+1 = 6,而6就是它们的朋友证号.给定一些整数,要求 ...

  2. cocos2d-x3.6 生成带类图的离线文档

    我的博客:http://blog.csdn.net/dawn_moon cocos2d-x的官网有点慢,并且最新3.6的在线API文档居然没有了类图,不知道什么原因,之前2.2.6都是有的. 只是能够 ...

  3. Ubuntu 14.04 或者16.04开启root账户登录和图形界面登录root时候的报错解决方法

    1.打开终端 2.输入sudo vi /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf 3.添加一行:greeter-show-manual-login ...

  4. Video Brightness Enhancement

    Tone Mapping原是摄影学中的一个术语,因为打印相片所能表现的亮度范围不足以表现现实世界中的亮度域,而如果简单的将真实世界的整个亮度域线性压缩到照片所能表现的亮度域内,则会在明暗两端同时丢失很 ...

  5. python实现并绘制 sigmoid函数,tanh函数,ReLU函数,PReLU函数

    Python绘制正余弦函数图像 # -*- coding:utf-8 -*- from matplotlib import pyplot as plt import numpy as np impor ...

  6. 简化Hadoop命令

    1. 安装客户端(通过端用户可以方便的和集群交互) 2. 简化Hadoop命令 修改~/.bashrcalias hadoop='/home/work/hadoop/client/hadoop-cli ...

  7. JavaScriptr -- 常用对象 String, date, prototype

    <script type="text/javascript"> //给已有的对象添加自定义功能 function getMax() { var max = this[0 ...

  8. bzoj 2005: [Noi2010]能量采集 筛法||欧拉||莫比乌斯

    2005: [Noi2010]能量采集 Time Limit: 10 Sec  Memory Limit: 552 MB[Submit][Status][Discuss] Description 栋栋 ...

  9. 常用的MySQL语句写法

    常用的MySQL语句写法 MySQL的SQL语句写法,除了那些基本的之外,还有一些也算比较常用的,这里记录下来,以便以后查找.     好记性不如烂笔头,这话说的太有道理了,一段时间不写它,还真容易忘 ...

  10. 浏览器访问web站点原理图

    启动tomcat,在浏览器中输入http://localhost:8080/web_kevin/hello.html,发生的事情如下: 1.浏览器解析主机名,即解析localhost.浏览器首先会到本 ...