剑指Offer-15-反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

包含迭代法和递归法

/*
public class ListNode {
    int val;
    ListNode next = null;

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

//第二种方法是构造空节点用头插法

第三种递归解法,newHead只保存头结点,链接由head完成

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;
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_27378875/article/details/81161798