/**
- 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;
}
// 递归体
// 创建一个next节点
ListNode next = head.next;
ListNode newhead = reverseList(next);
next.next=head;
head.next=null;
return newhead;
}
}
class Solution {
// 使用头插法
public ListNode reverseList(ListNode head) {
ListNode newhead = new ListNode(-1);
while (head != null) {
ListNode next = head.next;
head.next = newhead.next;
newhead.next = head;
head = next;
}
return newhead.next;
}
}