力扣第206号问题的三种解法
Posted *平芜尽处是春山*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣第206号问题的三种解法相关的知识,希望对你有一定的参考价值。
解法一、头插法
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;
运行截图:
以上是关于力扣第206号问题的三种解法的主要内容,如果未能解决你的问题,请参考以下文章