头依次拔下来,按顺序插进另一个链表:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: new_head=None while head: tmp=head.next head.next=new_head new_head=head head=tmp return new_head
执行用时 :44 ms, 在所有 python3 提交中击败了93.17%的用户
内存消耗 :14.9 MB, 在所有 python3 提交中击败了19.62%的用户
——2019.10.24
class Solution { public ListNode reverseList(ListNode head) { ListNode dump = new ListNode(-1); ListNode p = dump.next; ListNode q; while(head != null){ q = new ListNode(head.val); dump.next = q; q.next = p; p = q; head = head.next; } return dump.next; } }