public class Solution {
public ListNode reverseList(ListNode head) {
//起始
ListNode current=head;
ListNode previous=null;
ListNode next=null;
//反转,改变节点间的指向关系
while (current!=null){
next=current.next; //让next指向起始2
current.next=previous; //打断①→②
previous = current; //指针向右移动
current = next; //指针向右移动
}
head = previous;
return head;
}
}
python代码实现
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
current = head
previous = null
next = null
while current is not None:
next=current.next
current.next=previous
previous=current
current=next
head=previous
return head