class linkNode: def __init__(self,d=None): self.data = d self.next = None class linkString: def __init__(self): self.head = linkNode() self.size = 0 def StrAssign(self,s): #创建串 p = self.head for k,item in enumerate(s): tem = linkNode(item) p.next = tem p = tem self.size += 1 p.next = None def Distr(self): #输出 p = self.head j = self.size while p.next is not None and j >0: p = p.next print(p.data) j -= 1 def getsize(self): #输出串s的长度 p = self.head j = 0 while p.next is not None: p = p.next j += 1 print(j) def Instr(self,i,s1): #在串s的第9个字符位置插入串s1而产生串s2 if i<0 or i>self.size: raise ValueError("out of range") s2 = linkString() p = s2.head cur = self.head.next for _ in range(i): tem = linkNode(cur.data) p.next = tem p = tem s2.size += 1 cur = cur.next p_s = s1.head.next while s1.size>0 and p_s is not None: tem = linkNode(p_s.data) p.next = tem p = tem s2.size += 1 p_s = p_s.next while cur: tem = linkNode(cur.data) p.next = tem p = tem s2.size += 1 cur = cur.next p.next = None return s2 def DelStr(self,i,j): #删除串s的第2个字符开始的5个字符而产生串s2 if i<0 or i > self.size or i+j>self.size: raise ValueError("out of range") s2 = linkString() p = s2.head cur = self.head.next l = 0 while lself.size or i+j>self.size: raise ValueError("out of range") s2 = linkString() p = s2.head cur = self.head.next for _ in range(i): tem = linkNode(cur.data) p.next = tem p = tem s2.size += 1 cur = cur.next s_1 = s1.head.next while s_1: tem = linkNode(s_1.data) p.next = tem p = tem s2.size += 1 s_1 = s_1.next for _ in range(i,i+j): cur = cur.next while cur: tem = linkNode(cur.data) p.next = tem p = tem s2.size += 1 cur = cur.next return s2 def GetStr(self,i,j): #提取串s的第2个字符开始的10个字符而产生串s3 if i<0 or i>self.size or i+j>self.size: raise ValueError("out of range") s3 = linkString() p = s3.head cur = self.head.next for _ in range(i): cur = cur.next for _ in range(i,i+j): tem = linkNode(cur.data) p.next = tem p = tem s3.size += 1 cur = cur.next return s3 def Concat_str(self,s2): #将串s1和串s2连接起来而产生串s4 s4 = linkString() p = s4.head cur = self.head.next for _ in range(self.size): tem = linkNode(cur.data) p.next = tem p = tem s4.size += 1 cur = cur.next s_2 = s2.head.next while s_2: tem = linkNode(s_2.data) p.next = tem p = tem s4.size += 1 s_2 = s_2.next return s4 if __name__=='__main__': s_1 = "abcdefghefghijklmn" s1 = linkString() s1.StrAssign(s_1) s_2 = "xyz" s2 = linkString() s2.StrAssign(s_2) # a = s1.Instr(9,s2) # a = s1.DelStr(2,5) a = s1.RepStr(2,5,s2) # a = s1.GetStr(2,10) # a = s1.Concat_str(s2) a.Distr()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)