输入一个链表,反转链表后,输出新链表的表头。
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 class Solution: 7 # 返回ListNode 8 def ReverseList(self, pHead): 9 if pHead == None: 10 return None 11 head = pHead 12 nextnode = pHead.next 13 t = ListNode(0) 14 while head: 15 head.next = t.next 16 t.next = head 17 head = nextnode 18 if nextnode != None: 19 nextnode = nextnode.next 20 return t.next 21 # write code here
Java版,leetcode地址:
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 if (head == null) { 4 return null; 5 } 6 if (head.next == null) { 7 return head; 8 } 9 ListNode phead = head; 10 ListNode nextNode = head.next; 11 ListNode t = new ListNode(0); 12 while (phead != null) { 13 phead.next = t.next; 14 t.next = phead; 15 phead = nextNode; 16 if (nextNode != null) { 17 nextNode = nextNode.next; 18 } 19 } 20 return t.next; 21 } 22 }