题目:
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; } }