题目描述
输入一个链表,反转链表后,输出新链表的表头。
题目地址
思路
pHead始终指向要翻转的结点
last指向翻转后的首结点
每反转一个节点,把pHead的下一个节点指向last,last指向pHead成为反转后的首结点,在把pHead向前移动一个结点直至None结束
Python
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None # 单向链表链表 node1: 1->2->3 node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if not pHead or not pHead.next: return pHead last = None while pHead: temp = pHead.next pHead.next = last last = pHead pHead = temp return last if __name__ == '__main__': origin = node1 print('反转前:', end = ' ') while origin: print(origin.val, end = ' ') origin = origin.next result = Solution().ReverseList(node1) print('\n反转后:', end = ' ') while result: print(result.val, end = ' ') result = result.next
作者:huangqiancun
出处:http://www.cnblogs.com/huangqiancun/
本博客若无特殊说明则由作者原创发布,欢迎转载,但请注明出处 :)