def ConstructList(): i = 1 head = LNode() head.next = None tmp = None cur = head # 构造第一个链表 while i < 8: tmp = LNode() tmp.data = i tmp.next = None cur.next = tmp cur = tmp i += 1 return head
def add(h1, h2): if h1 is None or h1.next is None: return h2 if h2 is None or h2.next is None: return h1 c=0#记录进位 sums=0#记录两个节点相加的值 p1=h1.next p2=h2.next tmp=None#存储相加的和 resultHead=LNode()#相加后的链表的头节点 resultHead.next=None p=resultHead#用来指向链表resultHead最后一个节点 while p1 is not None and p2 is not None: tmp=LNode() sums=p1.data + p2.data + c tmp.data=sums % 10 c=int(sums/10) p.next = tmp#加入新链表 p=tmp p1=p1.next p2=p2.next #p2比p1长,p1比p2长 if p1 is None: while p2 is not None: tmp=LNode() sums=p2.data+c tmp.data=sums%10 c=int(sums/10) p.next=tmp p=tmp p2=p2.next if p2 is None: while p1 is not None: tmp=LNode() sums=p1.data+c tmp.data=sums%10 c=int(sums/10) p.next=tmp p=tmp p1=p1.next #完成全部计算后还有进位 if c==1: tmp=LNode() tmp.data=1 p.next=tmp return resultHead
while cur.next!=None: next=cur.next cur.next=pre pre=cur cur=cur.next cur=next cur.next = pre # 最后一个节点指向倒数第二个节点 head.next = cur if __name__ == '__main__': i=1 head=LNode(None) head.next=None tmp=None cur=head while i<8: tmp=LNode(i) tmp.next=None cur.next=tmp cur=tmp i+=1 print("逆序前:") cur=head.next while cur is not None: print(cur.data) cur=cur.next my_reverse(head)
tmp.data=sums%10 c=int(sums/10) p.next=tmp p=tmp p1=p1.next #完成全部计算后还有进位 if c==1: tmp=LNode() tmp.data=1 p.next=tmp return resultHead if __name__ == '__main__': i = 1 head1 = LNode() head1.next = None head2 = LNode() head2.next = None tmp = None cur = head1 addResult = None # 构造第一个链表 while i < 7: tmp = LNode() tmp.data = i + 2 tmp.next = None cur.next = tmp cur = tmp i += 1 cur = head2 # 构造第二个链表
if __name__ == '__main__': i = 1 head = LNode() tmp = None cur = head while i < 7: tmp = LNode() if i % 2 == 0: tmp.data = i + 1 elif i % 3 == 0: tmp.data = i - 2 else: tmp.data = i tmp.next = None cur.next = tmp cur = tmp i += 1 print("删除前:") cur = head.next while cur is not None: print(cur.data) cur = cur.next book_remove_dup(head) print("删除后:") cur = head.next while cur is not None: print(cur.data) cur = cur.next
def remove_node(p): if p.next is None or p is None: return False #无法删除 p_next = p.next next = p.next.next p.data = p_next.data p.next = next p_next.next = None return True if __name__ == "__main__": i = 1 head = LNode() # 链表头结点 head.next = None tmp = None cur = head p = None # 构造链表 while i < 8: tmp = LNode() tmp.data = i tmp.next = None cur.next = tmp cur = tmp if i == 5: p = tmp i += 1 print("删除结点" + str(p.data) + "前链表: ") printList(head)