解题思路
此处撰写解题思路
链表的反转就可以想到双指针
初始化当前指针cur指向head,前驱指针pre指向null
当cur!=null的时候就可以移动,先用临时指针保存cur.next
此时就可以让cur的下一个节点指向pre前驱,然后pre移动到cur
cur利用temp指针移动到cur.next
因为最后cur是到了null结束
所以返回的应该是pre
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode temp;
while(cur !=null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}