Ejemplo n.º 1
0
"""
方法功能: 把链表相邻元素逆序
输入参数: head:链表头结点
返回值:   操作后链表的头结点
"""
def reverse(head):
	if head is None or head.next is None:
		return head
	pre=head
	cur1=pre.next
	cur2=cur1.next
	while cur1!=None and cur2!=None:
		next=cur2.next
		pre.next=cur2
		cur2.next=cur1
		cur1.next=next
		if next!=None:
			pre=cur1
			cur1=next
			cur2=next.next
	return head
			
if __name__ == '__main__':
	head=makeList()
	print("链表",end=":")
	printList(head)
	reverse(head)
	print("翻转后",end=":")
	printList(head)
Ejemplo n.º 2
0
    while cur1 is not None and cur2 is not None:
        cur1 = cur1.next
        cur2 = cur2.next
        if cur1 == cur2:
            sameFistNode = cur1
            return sameFistNode
    return None


if __name__ == '__main__':
    # 构造链表并输出
    list1 = [1, 2, 3, 4]
    list2 = [11, 22, 33, 44, 55]
    sameList = [5, 6, 7, 8]
    sameHead = makeList(sameList)
    head1 = makeList(list1)
    last1 = getNode(head1, len(list1))
    last1.next = sameHead.next
    head2 = makeList(list2)
    last2 = getNode(head2, len(list2))
    last2.next = sameHead.next
    print("链表1", end=":")
    printList(head1)
    print("链表2", end=":")
    printList(head2)
    #判断链表是否交叉
    sameFistNode = isIntersect(head1, head2)
    if sameFistNode != None:
        print("链表交叉的第一个结点为%s" % sameFistNode.data)
    else:
        print("链表无交叉结点")
Ejemplo n.º 3
0
from linkedList1_5_2 import LinkedList,makeList,\
	findLastK,printList

"""
方法功能: 将单链表向右旋转k个位置 (目前k只能取在链表长度范围内)
输入参数: head:链表头结点; k:旋转位置
返回值:   newHead:旋转后的链表头结点
"""
def constructList(head,k):
	preKNode,lastNone=findLastK(head,k+1)
	head2=preKNode.next
	preKNode.next=None
	newHead=LinkedList("newHead")
	newHead.next=head2
	if head.next==None:
		return newHead
	else:
		lastNone.next=head.next
		return newHead

if __name__ == '__main__':
	head=makeList()
	print("链表",end=":")
	printList(head)
	k=1
	while k<7:
		head=makeList()
		print("将单链表向右旋转%s个位置后" % k, end=":")
		printList(constructList(head,k))
		k+=1