1.7 翻转相邻元素

2020-03-05  本文已影响0人  就是果味熊

示例:
1>2>3>4>5>6>7 -> 2>1>4>3>6>5>7

LNode文件

#%%
from LNode import LNode,LHead
#%%
def reverse_n_ele(head):
    if head == None or head.next == None:
        return head
    else:
        pre = head
        cur = head.next
        '''
        and只要左边的表达式为真,整个表达式返回的值是右边表达式的值。否则,返回左边表达式的值
        所以下列循环中,当列表为偶数个元素时,cur可以写cur.next
        '''
        while cur != None and cur.next != None: 
            inext = cur.next
            tmp = inext.next
            pre.next = inext
            inext.next = cur
            cur.next = tmp
            
            pre = cur
            cur = tmp
        return head
    
a = LHead()

list1,ab = a.create_ordered_list(6)
print(list1)

c = reverse_n_ele(ab)

print(c.get_ordered_list())
上一篇 下一篇

猜你喜欢

热点阅读