①迭代解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ListNode pre;
ListNode cur;
ListNode next;
public ListNode reverseList(ListNode head) {
cur=head;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
②递归解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head;
ListNode pre=null;
return recur(cur,pre);
}
public ListNode recur(ListNode cur,ListNode pre){
if(cur==null) return pre;
ListNode re=recur(cur.next,cur);
cur.next=pre;
return re;
}
}