采用三种方式实现链表反转

/**
 * @创建人 yumifen
 * @创建时间 2020/5/19
 * @描述  1 2 3 4 5 -> 5 4 3 2 1
 **/
public class ListNode2 {

    @Expose
    @Setter
    @Getter
    private  ListNode2  next;
    @Expose
    @Setter
    @Getter
    private  Integer    location;

    public ListNode2(ListNode2 next, Integer location) {
        this.next = next;
        this.location = location;
    }

    public ListNode2() {
    }

    /**
     * 头结点插入
     * @param listNode
     * @return
     */
    public static ListNode2 reverse0(ListNode2 listNode){
        //定义一个带头节点的
        ListNode2 resultList = new ListNode2(null,-1);
        //循环节点
        ListNode2 p = listNode;
        while(p!= null){
            //保存插入点之后的数据
            ListNode2 tempList = p.next;
            p.next = resultList.next;
            resultList.next = p;
            p = tempList;
        }
        return resultList.next;
    }

    /**
     * 以前的头变成尾
     * @param head
     * @return
     */
    private static ListNode2 reverse1(ListNode2 head){
        if (head == null||head.getNext()==null)
            return head;
        ListNode2 temp = head.getNext();
        ListNode2 newHead = reverse1(temp);    //这个是新的排序后的head
        temp.setNext(head);
        head.setNext(null);
        return newHead;
    }


    /**
     * 就地反转
     * @param head
     * @return
     */
    public static ListNode2 reverse2(ListNode2 head) {
        //单链表为空或只有一个节点,直接返回原单链表
        if (head == null || head.getNext() == null) {
            return head;
        }
        //前一个节点指针
        ListNode2 preNode = null;
        //当前节点指针
        ListNode2 curNode = head;
        //下一个节点指针
        ListNode2 nextNode = null;
        while (curNode != null) {
            nextNode = curNode.getNext();//nextNode 指向下一个节点
            curNode.setNext(preNode);//将当前节点next域指向前一个节点
            preNode = curNode;//preNode 指针向后移动
            curNode = nextNode;//curNode指针向后移动
        }
        return preNode;
    }

    public static void main(String[] args) {
//        ListNode2 head = new ListNode2(new ListNode2(null,2),1);
//        ListNode2 reverse = reverse0(head);
//        System.out.println("方法0:"+JsonUtil.object2Json(reverse));
        ListNode2 head2 = new ListNode2(new ListNode2(new ListNode2(null,3),2),1);
        ListNode2 reverse2 = reverse1(head2);
        System.out.println("方法1:"+JsonUtil.object2Json(reverse2));
//        ListNode2 head3 = new ListNode2(new ListNode2(null,2),1);
//        ListNode2 reverse3 = reverse2(head3);
//        System.out.println("方法2:"+JsonUtil.object2Json(reverse3));
    }
}

你可能感兴趣的:(算法)