LeetCode刷题1:反转链表


给你单链表的头节点,请你反转链表,并返回反转后的链表。

/*输入1,2,3,4,5
采用递归,栈顶首先为5,5.next=null,返回,此时为1->2->3->4->5;
栈顶为4,5.next=4,此时为1->2->3->4<->5,4.next=null,返回,此时为1->2->3->4<-5;
栈顶为3,4.next=3,此时为1->2->3<->4<-5,3.next=null,返回,此时为1->2->3<-4<-5;
2同上,返回为1->2<-3<-4<-5;
栈顶为1时,1<-2<-3<-4<-5;
此时newhead指向的结点为5;输出结果为5,4,3,2,1*/

//方法一递归法
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode newhead=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return newhead;
    }
}
//方法二迭代法,设置双指针
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head;
        ListNode pre=null;
        while(cur!=null){
            ListNode nodenext=cur.next;
            cur.next=pre;
            pre=cur;
            cur=nodenext;

        }
        return pre;
    }
}

相关