#链表初印象
#节点的实现
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: think
@file: node.py
@time: 2020/09/21
@desc:
"""
class Node (object):
'''节点'''
def __init__(self,elem):
self.elem=elem
self.next=None
class SingleLinkList(object):
def __init__(self):
self.head=None
def is_empty(self):
return self.__head==None
def length(self):
'''cur是指针,用来移动遍历节点'''
cur=self.__head
count=0
while cur!=None:
count+=1
cur=cur.next
return count
def add(self,item):
node=Node(item)
node.next=self.__head
self.__head=node
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
cur.next=node
def insert(self,pos,item):
'''pos从零开始'''
if pos<=0:
self.add(item)
elif pos>(self.length()-1):
self.append(item)
else:
pre=self.__head
count=0
while count<(pos-1):
count+=1
pre=pre.next
#当退出循环后,pre指向pre-1的位置
node=Node(item)
node.next=pre.next
pre.next=node
def remove(self,item):
cur=self.__head
pre=None
while cur!=None:
if cur.elem==item:
pre.next=cur.next
break
else:
pre=cur
cur=cur.next
single_obj=SingleLinkList()
single_obj.travel()
if __name__=="__main__":
li=SingleLinkList()
print(li.is_empty())
li.append(1)
print(li.is_empty())
li.append(2)
li.append(3)
li.append(4)