链表反转(python)

class node():
    def __init__(self,i):
        self.val=i
        self.nextp=None

def print_(currp):
    print(currp.val)
    while 1:
        currp = currp.nextp
        print(currp.val)
        if not currp.nextp:
            break

def rev(phead):
    prep = phead
    currp = phead.nextp
    phead.nextp = None  # 务必归空,否则无限循环1、2节点
    tmpp = currp.nextp
    currp.nextp = prep
    while tmpp:
        prep = currp
        currp = tmpp
        tmpp = currp.nextp
        currp.nextp = prep
    return currp

while 1:
    i=int(input('请输入节点数:\n'))
    if i<1:
        print('输入错误')
    elif i==1:
        print(1)
        print('反转结果:')
        print(1)
    elif i==2:
        phead=node(1)
        phead.nextp=node(2)
        print_(phead)
        print('反转结果:')
        currp=phead.nextp
        currp.nextp=phead
        phead.nextp=None
        print_(currp)
    if i>=3:
        phead=node(1)
        phead.nextp=node(2)
        currp=phead.nextp
        for j in range(i-2):
            currp.nextp=node(j+3)
            currp=currp.nextp
        print_(phead)
        phead=rev(phead)
        print('反转结果:')
        print_(phead)

你可能感兴趣的:(链表反转(python))