此题较为简单,重点在于声明一个指针用来保存head.next节点,然后head往前指,然后往后遍历,时间复杂度为O(n),空间复杂度为O(1)。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = p;
p = head;
head = next;
}
return p;
}
}