python 实现链表反转

185 阅读1分钟

代码:

#实现链表反转
#1>2>3>4>5  转成5>4>3>2>1
#先实现一个链表
class Node():
    def __init__(self,data = None,next = None):
        self.data = data
        self.next = next
class my_list(Node):
    def __init__(self,head = None):
        self.head =Node(head)
    def add_value(self,data):
        data = Node(data)
        cur = self.head
        if cur is None:
            self.head = data
        while cur.next is not None:
            cur = cur.next
        cur.next = data

    def print_list(self):
        cur = self.head
        while cur.next is not None:
            cur = cur.next
            print(cur.data)
def reverse_list(l):
    ll = my_list()
    head = l.head
    if head is None or head.next is None:
        return None
    n = None
    pre = None
    while head is not None:
        n = head.next
        head.next = pre
        pre = head
        head = n
    ll.head = pre
    return ll

def reverse_list2(l):
    count = 0
    if l.head == None:
        return None
    elif l.head.next == None:
        return l.head
    elif l.head.next.next == None:
        tmp = l.head.next
        l.head.next = l.head
        l.head = tmp
        return l.head
    else:
        head = l.head
        p = head.next
        tmp = head.next.next
        while True:
            p.next = head

            if count == 0:
                p.next = None

            head = p
            p = tmp
            tmp = tmp.next

            if tmp.next == None:
                p.next = head
                head = p
                break

    return head

l = my_list()
for i in range(1,6):
    l.add_value(i)
l.print_list()
ll = reverse_list(l)
ll.print_list()