首页 > 技术文章 > Leetcode单链表反转

Knight66666 2020-04-24 09:21 原文


public class ListNode {

        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }

    public void setNext(ListNode next) {
            this.next = next;

    }
}

 

public class class_leetcode_反转一个链表 {
    public static 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;
    }

    public static ListNode reverseList2(ListNode head){
        if(head==null||head.next == null){
            return head;
        }
       ListNode newHead = null;
        while(head!=null){
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }




    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode p1 = new ListNode(2);
        ListNode p2 = new ListNode(3);
        ListNode p3 = new ListNode(4);
        ListNode p4 = new ListNode(5);
        head.setNext(p1);
        p1.setNext(p2);
        p2.setNext(p3);
        p3.setNext(p4);

        ListNode aa = head;
        while(head.next!=null)
        {
            System.out.println(head.val);
            head = head.next;
        }
        System.out.println(head.val);

        ListNode A = reverseList2(aa);
        while(A.next!=null)
        {
            System.out.println(A.val);
            A = A.next;
        }
        System.out.println(A.val);



    }

}

 

推荐阅读