方法一:(递归)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) {
return head;
}
ListNode res=reverseList(head.next);
head.next.next=head;
head.next=null;
return res;
}
}
方法二:(迭代)
/**
* 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 pre=null;
ListNode curr=head;
while(curr!=null) {
ListNode nextTemp=curr.next;
curr.next=pre;
pre=curr;
curr=nextTemp;
}
return pre;
}
}