LeetCode.206 Reverse Linked List

xiaoxiao2021-02-28  172

题目:

Reverse a singly linked list.

分析:

1.非递归实现

/** * 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)return null; ListNode res=new ListNode(0); ListNode pre=head; while(pre!=null){ ListNode cur=pre.next; pre.next=res.next; res.next=pre; pre=cur; } return res.next; } } 2.递归实现

class Solution { public ListNode reverseList(ListNode head) { //递归实现链表逆序 if(head==null)return null; //出口 if(head.next==null){ return head; } ListNode pre=head.next; ListNode cur=reverseList(pre); //断链 head.next=null; pre.next=head; return cur; } }

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

最新回复(0)