一、问题描述
Reverse a singly linked list.
二、问题分析
利用三个指针pre、nxt、cur,最后返回指针pre。
三、算法代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
ListNode nxt = head.next;
ListNode cur = head;
while(nxt != null){
nxt = head.next;
head.next = pre;
pre = head;
head = nxt;
}
return pre; //不能return head,此时head指针为空
}
}