python 单链表反转,Python列表反转

  python 单链表反转,Python列表反转

  顾名思义,概念链表就像一个链表,是相对于线性链表的线性顺序表。两者的区别在于,线性链表必须在内存中打开一个连续的空间,所以内存中存储的数据是连续的,而线性链表是随机存储在内存中的,数据之间的联系依赖于指针。

  存储结构

  class listnode 3360 def _ init _(self,val):self . val=val self . next=none创建单个链接列表

  Defcreatelist(array): # array为列表类型,对应数据结构中的线性序列表head=list node(head)headforvalinaray 3360 node=listte)head)

  def traverse(head):p=head while(p)p):print(p . val)p=p . next print)。

  Defgetelem(head,I): # head是链表开头的节点# i应该读取节点位置p=head count=1 # counter while(p)p):if count==I 3360

  指针p必须比计数器慢一个位置,因为节点必须插入到指定的位置。单链表不能追溯到前一个节点,但双链表可以追溯到前一个节点。

  definesertelem(head,insertVal,I):# head是链表的开始节点# insertVal是应该插入的节点的值# I是要插入的节点的位置p=head count=1 ifi==13360 node=list node(insert val),即node . next=preturnnodehill(p):count=1

  与插入操作一样,必须删除指定位置的节点。p指针比计数器慢一步。只要删除结点的前一个结点的指针指向删除结点的后一个结点,删除的节点就会自动释放。

  在defdeleteelem(head,I): # head中,链表开头的节点# i是要删除的节点的位置。p=head count=1 ifi==1:return p . next while(pandp . NDP)360 count=1 if count==I:p . next=p . next . nextreturnheadp=

  原list1,list2defmergelist(list1,list 2)3360 P1=list 1 p 2=list 2 list 3=list node(head)P3=list 3 while(P1 and p2):if P1 . val p2 . val 3360 # P1 . nep3p 2 p 3 . next=P2P 2=p2 . nextp 3=P3 . nextif P1:# P1其余为P3.next=P1IFP220 p2其余为p3.next=p2返回list3.next循环。因此,创建链表时,最后一个节点必须指向第一个节点。

  #创建单个链表defcreatelist(Array):)数组的类型为list。对应数据结构的线性序列表head=list node(head)(p=headforvalinaray 3360 node=list node)val)p . next=nodep=p . nextreturnhead数组是列表类型,对应数据结构的线性序列表head=list node(head)(p=headforvalinarry 3360 node=list node)val)p . next=nodep=p . nextp . next=对于源码来说,创建、插入和删除都是不同的,因为所有的读取都和单链表、双链表一样顾名思义,双向链表可以双向遍历,所以创建双向链表时可以返回起始节点和结束节点的指针。

  创建defcreatelist(Array): # array作为列表类型,对应数据结构的线性序列表head=dullistnode(head)(p=headforvalinarry 3360 node=dullistnode(val))p是definertelem(head,insertVal,I): # header是链表的开始节点# insertVal是应该插入的节点的值# I是应该插入的节点的位置p=head=1 ifi==13360 node=dullistnode(insert val),也就是说, nodereturnodewith(p insert val)))))))62 node . next=p . nextifnode . next:p . next . pre=nodep . next=node node . prode . prodei是要删除的节点的位置p=head number=1 ifi==1:p . next . pre=none turgh . next while(pandp . next))。 3360 count=1 if count==I:delete node=p . nextp . next=delete node . next:delete node . next . pext

  原list1,list2defmergelist(list1,list 2)3360 P1=list 1 p 2=list 2 list 3=dul list node(head)P3=list 3 while(P1 and p2):如果P1 . val p2 . val 3360 # P1 . val 3360 # P1 # P1 . p3p2p 3 . next=P2P 2 . pre=p3p 2 . nextp 3=P3 . nextifp 13360 # P1,其余为P3 . next=P1 . pre=p3ifp 2:# P2,其余为P3。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: