解法一、头插法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode node = new ListNode(head.val);
node.next = newHead;
newHead = node;
head = head.next;
}
return newHead;
}
}
运行截图:
解法二、原地修改链表
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}
运行截图:
解法三、递归法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode secNode = head.next;
ListNode newHead = reverseList(head.next);
secNode.next = head;
head.next = null;
return newHead;
}
}
运行截图: