开始刷数据结构了。
1.递归
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode ReverseList (ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode reverseHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return reverseHead;
}
}
2.非递归
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode ReverseList (ListNode head) {
ListNode cur = head;
ListNode next = null;
ListNode pre = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
标签:head,ListNode,val,反转,next,链表,BM1,null,public
From: https://www.cnblogs.com/chengyiyuki/p/18130887