剑指offer-反转链表-java

xiaoxiao2021-02-28  34

题目描述:

输入一个链表,反转链表后,输出链表的所有元素。

思路解析:

非递归方法:新建一个ListNode链表头节点pre,然后把原来的链表从前到后摘下来,此时需要一个next保存后边的节点。然后摘下来的head的下一个节点设置成pre,循环直到head为null。

递归方法:

找到链表的最后一个节点,作为头节点;设置其下一个节点为head;设置head的下一个节点为null;

代码:

非递归方法:

public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { public ListNode ReverseList(ListNode head) { ListNode pre=null; if(head==null){ return null; } while(head!=null){ ListNode temp=head.next; head.next=pre; pre=head; head=temp; } return pre; } }

递归方法:

public class Solution { public ListNode ReverseList(ListNode head) { if(head==null||head.next==null){ return head; } ListNode pre=ReverseList(head.next); head.next.next=head; head.next=null; return pre; } }

转载请注明原文地址: https://www.6miu.com/read-2613805.html

最新回复(0)