链表的操作要注意当前的所在位置,你要操作数据的所在位置,要如何去找到你要操作的数据。
链表结点的定义:
"""结点定义方法1"""
class LNode1():
""" 定义好后再调用的时候不需要传值,直接head=LNode() """
data=None
next=None
"""结点定义方法2"""
class LNode2:
""" 定义好后再调用的时候需要传值,head=LNode(None,None) """
def __init__(self,data,_next = None):
self.data = data
self._next = _next
def __repr__(self):
'''用来定义LNode的字节输出'''
return str(self.data)
"""结点定义方法3"""
class LNode3:
"""定义后的结点需要传入data的值,head=LNode(None)"""
def __init__(self,x):
self.data=x
self.next=None
"""结点定义方法4"""
class LNode4:
"""定义后的结点需要传入data的值,head=LNode()"""
def __init__(self):
self.data=None
self.next=None
"""在结点使用时的方法都是一样的,通过head.next创建结点的下一个或者等于其他结点"""
使用定义好的结点来创建一个简单的链表:
"""链表的创建"""
def CreateLink():
i=1
head=LNode1()
"""给链表赋初值,头结点"""
# head.data=520
# head.next=None
tmp=None
cur=head
while i<8:
tmp=LNode1()
tmp.data=i
tmp.next=None
cur.next=tmp
cur=tmp
i+=1
return head
将一个数组或者其他类型的数据放进链表中,以数组数据为例,只需要的传入值以及赋值的时候改成赋予相应的值就行:
def CreateLink1(listdata):
head=LNode1()
"""给链表赋初值,头结点"""
# head.data=520
# head.next=None
tmp=None
cur=head
for i in range(len(listdata)):
tmp=LNode1()
tmp.data=listdata[i]
tmp.next=None
cur.next=tmp
cur=tmp
i+=1
return head
打印显示创建好的链表:
def ShowLink(head):
"""如果head.next则不显示原来链表的头结点的值,如果直接head的话则显示520"""
cur=head.next
#cur=head
while cur!=None:
print(cur.data)
cur=cur.next
链表的删除,如果链表中存在指定的数值,则从链表中将其删除,没有则不管:
"""链表中元素的删除通过遍历链表找到需要删除head.data的元素进行删除"""
def remove(head,data):
"""通过查找删除链表中指定的所有数值"""
if head==None or head.next==None:
return
cur=head
tmp=None
tmp=head.next
while tmp!=None:
if tmp.data==data:#将下一个结点给cur,tmp自己往后走一个结点
cur.next=tmp.next
tmp=cur.next
else:#维持原有结点不变
tmp=tmp.next
cur=cur.next
return head
链表去重,删除第二及以后出现的相同元素,保留第一次出现的:
"""链表去重,删除重复出现的,利用两个while语句实现for循环遍历去重"""
def removerepation(head):
if head==None or head.next==None:
return
pre=None
cur=head.next
tmp=None#依次与cur中的每一个data进行比较,如果重复出现就删除
while cur!=None:
tmp=cur.next
pre=cur
while tmp!=None:
if cur.data==tmp.data:#删除重复的
pre.next=tmp.next
tmp=tmp.next
else:#继续往后走
pre=tmp
tmp=tmp.next
cur=cur.next
return head
链表翻转:
"""链表翻转"""
def reverse(head):
if head==None or head.next==None:
return
cur=None
next=None
cur=head.next.next#将链表的第一个结点设置为尾结点
head.next.next=None
while cur!=None:
next=cur.next
cur.next=head.next
head.next=cur
cur=next
return head