#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Node:
def __init__(self,data):
self.data = data
self.next = None
class SingleLinkList:
def __init__(self):
self.__head = None
def is_empty(self):
return self.head == None
def length(self):
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
cur = self.__head
while cur != None:
print(cur.data)
cur = cur.next
print ""
def add(self,data):
node = Node(data)
node.next = self.__head
self.__head = node
def append(self,data):
node = Node(data)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
def insert(self,pos,data):
if pos <= 0:
self.add(data)
elif pos > (self.length() - 1):
self.append(data)
else:
node = Node(data)
count = 0
pre = self.__head
while count < (pos -1):
count += 1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self,data):
cur = self.__head
pre = None
while cur != None:
if cur.data == data:
if not pre:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def search(self,data):
cur = self.__head
while cur != None:
if cur.data == data:
return True
cur = cur.next
return False
单链表的简单操作
最新推荐文章于 2020-03-13 15:54:32 发布