Python链表与反链表
# -*- coding:utf8 -*-
#/usr/bin/env python class Node(object):
def __init__(self, data, pnext = None):
self.data = data
self._next = pnext
print('self._next',self._next) def __repr__(self):
return str(self.data) class ChainTable(object):
def __init__(self):
self.head = None
self.length = 0 def isEmpty(self):
return (self.length == 0) def append(self, dataOrNode):
item = None
print('Node',Node)
if isinstance(dataOrNode, Node):
item = dataOrNode
print(123)
else:
item = Node(dataOrNode)
print(item,456)
if not self.head:
self.head = item
self.length += 1
print('self.head',self.head._next)
else:
node = self.head
print('1111node',node)
print('111node._next',node._next)
while node._next:
print(222222222222222222222222,node._next)
node = node._next
print(444444444444444,node)
node._next = item
print(11111111111111111111111,node._next)
self.length += 1 def reverseChainTable(self,chaintable):
if isinstance(chaintable, Node):
item = chaintable
print(123)
else:
print('这不是链表')
return def delete(self, index):
if self.isEmpty():
print ("this chain table is empty.")
return if index < 0 or index >= self.length:
print ('error: out of index')
return if index == 0:
self.head = self.head._next
self.length -= 1
return j = 0
node = self.head
prev = self.head
while node._next and j < index:
prev = node
node = node._next
j += 1 if j == index:
prev._next = node._next
self.length -= 1 def insert(self, index, dataOrNode):
if self.isEmpty():
print ("this chain tabale is empty")
return if index < 0 or index >= self.length:
print ("error: out of index")
return item = None
if isinstance(dataOrNode, Node):
item = dataOrNode
else:
item = Node(dataOrNode) if index == 0:
item._next = self.head
self.head = item
self.length += 1
return j = 0
node = self.head
prev = self.head
while node._next and j < index:
prev = node
node = node._next
j += 1 if j == index:
item._next = node
prev._next = item
self.length += 1 def update(self, index, data):
if self.isEmpty() or index < 0 or index >= self.length:
print ('error: out of index')
return
j = 0
node = self.head
while node._next and j < index:
node = node._next
j += 1 if j == index:
node.data = data def getItem(self, index):
if self.isEmpty() or index < 0 or index >= self.length:
print ("error: out of index")
return
j = 0
node = self.head
while node._next and j < index:
node = node._next
j += 1 return node.data def getIndex(self, data):
j = 0
if self.isEmpty():
print ("this chain table is empty")
return
node = self.head
while node:
if node.data == data:
return j
node = node._next
j += 1 if j == self.length:
print ("%s not found" % str(data))
return def clear(self):
self.head = None
self.length = 0 def __repr__(self):
if self.isEmpty():
return "empty chain table"
node = self.head
nlist = ''
while node:
nlist += str(node.data) + ' '
node = node._next
return nlist def __getitem__(self, ind):
if self.isEmpty() or ind < 0 or ind >= self.length:
print ("error: out of index")
return
return self.getItem(ind) def __setitem__(self, ind, val):
if self.isEmpty() or ind < 0 or ind >= self.length:
print ("error: out of index")
return
self.update(ind, val) def __len__(self):
return self.length chariin = ChainTable()
for i in range(10):
chariin.append(i) print(chariin)
从哪里找的忘了,不过思路已经整的很明白了
下面是链表翻转的:
来源 https://blog.csdn.net/u011608357/article/details/36933337
单链表的反转可以使用循环,也可以使用递归的方式
1.循环反转单链表
循环的方法中,使用pre指向前一个结点,cur指向当前结点,每次把cur->next指向pre即可。
class ListNode:
def __init__(self,x):
self.val=x;
self.next=None; def nonrecurse(head): #循环的方法反转链表
if head is None or head.next is None:
return head;
pre=None;
cur=head;
h=head;
while cur:
h=cur;
tmp=cur.next;
cur.next=pre;
pre=cur;
cur=tmp;
return h; head=ListNode(1); #测试代码
p1=ListNode(2); #建立链表1->2->3->4->None;
p2=ListNode(3);
p3=ListNode(4);
head.next=p1;
p1.next=p2;
p2.next=p3;
p=nonrecurse(head); #输出链表 4->3->2->1->None
while p:
print p.val;
p=p.next;
反转代码:
class ListNode:
def __init__(self,x):
self.val=x;
self.next=None; def recurse(head,newhead): #递归,head为原链表的头结点,newhead为反转后链表的头结点
if head is None:
return ;
if head.next is None:
newhead=head;
else :
newhead=recurse(head.next,newhead);
head.next.next=head;
head.next=None;
return newhead; head=ListNode(1); #测试代码
p1=ListNode(2); # 建立链表1->2->3->4->None
p2=ListNode(3);
p3=ListNode(4);
head.next=p1;
p1.next=p2;
p2.next=p3;
newhead=None;
p=recurse(head,newhead); #输出链表4->3->2->1->None
while p:
print p.val;
p=p.next;
Python链表与反链表的更多相关文章
- python数据结构与算法——链表
具体的数据结构可以参考下面的这两篇博客: python 数据结构之单链表的实现: http://www.cnblogs.com/yupeng/p/3413763.html python 数据结构之双向 ...
- python数据结构链表之单向链表
单向链表 单向链表也叫单链表,是链表中最简单的一种形式,它的每个节点包含两个域,一个信息域(元素域)和一个链接域.这个链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值. 表元素域ele ...
- Python数据结构应用3——链表
linked list(链表) 建立 Node 链表的基本组成就是一个个Node,每个Node都需要包括两部分内容,一部分是自身的data,另一部分是下一个Node的reference. class ...
- python实现数据结构单链表
#python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" ...
- Python线性表——单链表
1. 线性表简介 线性表是一种线性结构,它是由零个或多个数据元素构成的有限序列.线性表的特征是在一个序列中,除了头尾元素,每个元素都有且只有一个直接前驱,有且只有一个直接后继,而序列头元素没有直接前驱 ...
- Python数据结构之单链表
Python数据结构之单链表 单链表有后继结点,无前继结点. 以下实现: 创建单链表 打印单链表 获取单链表的长度 判断单链表是否为空 在单链表后插入数据 获取单链表指定位置的数据 获取单链表指定元素 ...
- python 数据结构中的链表操作
链表的定义: 链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址.由于每个结点都包含了可以链接起来的地址信息,所以用一个变量就 ...
- Python与数据结构[0] -> 链表/LinkedList[0] -> 单链表与带表头单链表的 Python 实现
单链表 / Linked List 目录 单链表 带表头单链表 链表是一种基本的线性数据结构,在C语言中,这种数据结构通过指针实现,由于存储空间不要求连续性,因此插入和删除操作将变得十分快速.下面将利 ...
- Python与数据结构[0] -> 链表/LinkedList[1] -> 双链表与循环双链表的 Python 实现
双链表 / Doubly Linked List 目录 双链表 循环双链表 1 双链表 双链表和单链表的不同之处在于,双链表需要多增加一个域(C语言),即在Python中需要多增加一个属性,用于存储指 ...
随机推荐
- UVa 11609 组队(快速幂)
https://vjudge.net/problem/UVA-11609 题意: 有n个人,选一个或多个人参加比赛,其中一名当队长,有多少种方案?如果参赛者完全相同,但队长不同,算作不同的方案. 思路 ...
- c++ 反转容器的元素顺序(reverse)
#include <vector> #include <iostream> #include <iterator> #include <algorithm&g ...
- 利用JS将页面中包含“一个”字段值的元素改为红色
document.body.innerHTML = document.body.innerHTML.replace(/一个/ig,"<span style='color: red;'& ...
- 基于Oracle的SQL优化(崔华著)-整理笔记-工具集
一.脚本display_cursor_9i.sql是可以得到SQL的真实执行计划,使用示例 使用示例,请看以下case 1.执行测试sql: SELECT T1.*,T2.* FROM T_0504 ...
- 使用POI动态更新导出的EXCEL模板中的列
基本思路: 1.从附件服务器上取得模板的流文件 2.拿到流文件之后再使用workbook.write(outs);方法改变流文件中的数据. else if (pageContext.getParame ...
- C++设计与声明——让接口容易被正确使用
一个简答易错的例子 class Date { public Date(int month,int day,int year); } 一年后使用这个接口的时候,写了Date d(15,10,2015)或 ...
- CF 148D Bag of mice 概率dp 难度:0
D. Bag of mice time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- 非关联容器|hash|unordered_map/multimap,unordered_set/multiset
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- 分析hello.java文件
使用JavaServer Faces技术的Web模块示例 1.hello1: hello1应用程序是一个web模块,它使用JavaServer Faces技术来显示问候和响应.可以使用文本编辑器查看应 ...
- Pale Moon 苍月浏览器 24.0.1 发布
火狐浏览器知名修改版—苍月浏览器Pale Moon今天发布24.0.1版本,该版本基于Firefox 最近更新的24.0.1正式版. 下载地址: 32位下载:http://relmirror.pale ...