给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
1.双指针法:
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;
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
2.递归法:
/**
* 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) {
return reverseList(head,null);
}
public ListNode reverseList(ListNode cur,ListNode pre) {
if(cur==null){
return pre;
}
ListNode temp=cur.next;
ListNode result=reverseList(temp,cur);
cur.next=pre;
return result;
}
}