Reverse a singly linked list.
Subscribe to see which companies asked this question
//递归
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode tmp =head.next;
head.next=null;
ListNode rev_list=reverseList(tmp);
tmp.next=head;
return rev_list;
}
}
//非递归
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode t1=head;
ListNode t2 =head.next;
head.next=null;
while(t2!=null){
ListNode t3=t2.next;
t2.next=t1;
t1=t2;
t2=t3;
}
return t1;
}
}