單鏈表的新增 刪除 合併 Python
阿新 • • 發佈:2018-12-14
節點實現:
class SingleNode(object):
def __init__(self,item):
self.val = item
self.next = None
指定位置新增元素:
def insert(self,head, pos,item): node = SingleNode(item) cur = self.head count = 0 while cur != None: count +=1 cur = cur.next if pos<=0: node.next = self.head #將新節點指向頭節點,即指向頭節點的位置 self.head = node #將連結串列的頭head 指向新節點 elif pos>=cout: if self.head == None: self.head = node else: fin =self.head while fin.next != None: fin = fin.next cur.next = node else: c =0 pre = slef.head while c < pos -1 : c +=1 pre = pre.next node.next =pre.next pre.next = node
刪除節點:
def remove (self ,item):
cur = self.head
pre =None
while cur != None:
if cur.val = item:
if not pre:
self.head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
指定倒數n個位置刪除節點:
Class ListNode: def __init__(self,x): self.val = x self.next = None Class Solution: def removeNthFromEnd(self,head,n): fast = slow = head for i in range(n): fast= fast.next if not fast: return head.next while fast.next: fast = fast.next slow= slow.next slow.next =slow.next.next return head
有序連結串列合併
def mergeTwoLists1(self, l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next # recursively def mergeTwoLists2(self, l1, l2): if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2