单链表的添加 删除 合并 Python

节点实现:

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

猜你喜欢

转载自blog.csdn.net/weixin_40732844/article/details/85001598