要求反转单链表 分析做临时指针temp、新指针newhead、原链表指针cur; 把temp,cur.next,newhead,cur四个值进行赋值变化: temp=cur.next cur.next=newHead newHead = cur cur = temp 原有链表phead:1-2-3-4-5-6-7-8-9 初始赋值:cur:1-2-3-4-5-6-7-8-9 newhead:None temp:None 第一次循环: cur.next:None newhead:1 temp:2-3-4-5-6-7-8-9 cur:2-3-4-5-6-7-8-9 第二次循环: cur.next:1 newhead:2-1 temp:3-4-5-6-7-8-9 cur:3-4-5-6-7-8--9
代码: class Node: def __init__(self,data=None,next=None): self.data=data self.next=next def reverse(pHead): if pHead == None or pHead.next == None: return pHead cur = pHead newHead = None temp = None while cur: temp=cur.next cur.next=newHead newHead = cur cur = temp return newHead if __name__ == '__main__': pHead = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) list=reverse(pHead) while list: print(list.data) list= list.next
运行:
9
8
7
6
5
4
3
2
1
Process finished with exit code 0