python链表 —— 把链表相邻元素翻转

题目描述:

把链表相邻的结点看成一组进行翻转。假设给定链表1—>2—>3—>4—>5—>6—>7—>8,那么翻转后的链表变为2—>1—>4 —> 3 —> 6 — >5 — >7。

算法思想:就地逆序

通过调整指针域的指向直接调换响铃的两个节点。如果单链表恰好有偶数个节点,那么只需要将就节点对调即可,如果链表有基数个节点,那么只需要将除了最后一个节点之外的其他节点进行久对换即可。

算法性能:

时间复杂度为o(n),空间复杂度为o(1)

代码实现: 

class Node(object):
    def __init__(self, item):
        self.data = item
        self.next = None

#把链表的相邻元素翻转
def reverse(head):
    if head is None or head.next is None:
        return
    cur = head.next
    pre = head
    next = None
    #print("ooooooooooo")
    #print(cur.data)
    #print(next.data)
    while cur is not None and cur.next is not None:
        #next= cur.next.next
        #pre.next = cur.next
        #cur.next.next = cur
        #cur.next = next
        #pre = cur                
        #cur = next
        next = cur.next
        cur.next = next.next
        next.next = cur
        pre.next = next
        pre = cur
        cur = cur.next


if __name__ == "__main__":
    i = 1
    head = Node(None)
    head.next = None
    tmp = None
    cur = head
    while i < 8:
        tmp = Node(i)
        tmp.next = None
        cur.next = tmp
        cur = tmp
        i += 1
    print("\n没有翻转前:")
    cur = head.next
    while cur is not None:
        print(cur.data,end=" ")
        cur = cur.next
    reverse(head)
    print("\n翻转之后:")
    cur = head.next
    while cur is not None:
        print(cur.data, end=" ")
        cur = cur.next

代码运行结果为:

没有翻转前:
1 2 3 4 5 6 7 
翻转之后:
2 1 4 3 6 5 7 

 

你可能感兴趣的:(小菜鸟的python进阶之路,数据结构与算法)