题目描述
输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
1.双指针
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null) return null;
ListNode pre = null;//保存head的前一个结点
ListNode next = null;//保存head的后一个结点
while(head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
2.递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null||head.next == null){
return head;
}
ListNode cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}