单链表反转

链表初始化

public class ListNode {

    int value;
    ListNode next;

    public ListNode(int value){
        this.value = value;
    }
  }

递归实现

/**
     * 递归实现
     * @param head
     * @return
     */
    public static ListNode invertList(ListNode head){
        if(head == null || head.getNext() == null){
            return head;
        }

        ListNode newhead = invertList(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return newhead;
    }

非递归实现

 /**
     * 非递归反转链表,最开始是头结点和前面pre null结点反转,然后依次进行的
     * @param head
     * @return
     */
    public static ListNode invertListNonRecursion(ListNode head){
        if(head == null || head.getNext() == null){
            return head;
        }
        ListNode pre = null;
        ListNode next = null;
        while(head != null){
            next = head.getNext();
            head.setNext(pre);
            pre = head;
            head = next;
        }
        return pre;
    }

参考资料

反转单向链表

你可能感兴趣的:(Data,structure,单链表,反转)