在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. Spring注解式与配置文件式

    http://tom-seed.iteye.com/blog/1584632 Spring注解方式bean容器管理 1.通过在配置文件中配置spring组件注入 <context:compone ...

  2. LeetCode:范围求和||【598】

    LeetCode:范围求和||[598] 题目描述 给定一个初始元素全部为 0,大小为 m*n 的矩阵 M 以及在 M 上的一系列更新操作. 操作用二维数组表示,其中的每个操作用一个含有两个正整数 a ...

  3. SpringBoot学习笔记(7):Druid使用心得

    SpringBoot学习笔记(7):Druid使用心得 快速开始 添加依赖 <dependency> <groupId>com.alibaba</groupId> ...

  4. mysql主从复制(windows下)

    简单搭建mysql主从服务器(双向复制),仅供学习之用. 1.下载mysql-advanced-5.6.16-winx64.zip 下载完成后解压,重命名成mysql,分别放入两台服务器(看第二点集群 ...

  5. Data Structure Graph: prim

    最小生成树算法.这里的s是可以随意选取的,不影响树的生成,但是不同的s有不同的dis #include <iostream> #include <vector> #includ ...

  6. Data Structure Array: Given an array of of size n and a number k, find all elements that appear more than n/k times

    http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-tha ...

  7. 【LeetCode】合并两个有序链表

    将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2->4, 1->3->4 输出:1->1->2- ...

  8. 算法(Algorithms)第4版 练习 1.5.12

    package com.qiusongde; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; pu ...

  9. mvc购物车项目

    第一个mvc项目--购物车. 1.购物车需求 a.用户可以登录 b.用户可以购买商品 c.用户可以对购物车的商品进行修改和删除 d.用户可以下订单 e.系统可以发送电子邮件给用户 uml图 2.界面设 ...

  10. jQuery - 获取/设置内容和属性

    获得内容 - text().html() 以及 val() 三个简单实用的用于 DOM 操作的 jQuery 方法: text() - 设置或返回所选元素的文本内容 html() - 设置或返回所选元 ...