美文网首页
单链表反转

单链表反转

作者: zhangmz | 来源:发表于2020-06-11 08:43 被阅读0次
    /**
    * 节点定义
    **/
    static class Node {
            Integer data;
            Node next;
    
            @Override
            public String toString() {
                return this.data.toString();
            }
     }
    /**
    * 生成节点数据
    **/
    static Node readyNode() {
            Node linkNode1 = new Node();
            linkNode1.data = 1;
            Node linkNode2 = new Node();
            linkNode2.data = 2;
            Node linkNode3 = new Node();
            linkNode3.data = 3;
            Node linkNode4 = new Node();
            linkNode4.data = 4;
            Node linkNode5 = new Node();
            linkNode5.data = 5;
            Node linkNode6 = new Node();
            linkNode6.data = 6;
            linkNode1.next = linkNode2;
            linkNode2.next = linkNode3;
            linkNode3.next = linkNode4;
            linkNode4.next = linkNode5;
            linkNode5.next = linkNode6;
            return linkNode1;
        }
    
    /**
    * 递归方式反转
    **/
    static Node reverse(Node head) {
            //我们从原链表的头结点开始
            Node cur = head;
            //递归到原链表的尾节点结束。递归到了尾节点的时候就返回当前节点
            if(cur.next == null){
                return cur;
            }else{
                Node reHead = reverse(cur.next);
                cur.next.next = cur;
                cur.next = null;
                return reHead;
            }
    
        }
    
    /**
    * 循环方式反转
    **/
    static Node reverse2(Node pHead) {
            if (pHead == null) {
                return pHead;
            }
            Node prev = null;
            while (pHead != null) {
                //保存next
                Node temp = pHead.next;
                //反转
                pHead.next = prev;
                //移动prev
                prev = pHead;
                //移动pHead
                pHead = temp;
            }
            return prev;
        }
    
    /**
    ** 内置法
    ** LinkedList没有提供反转链表的相关函数,以下是通过foreach实现链表反转
    **/
    static LinkedList reverse(LinkedList linkedList) {
        LinkedList<Object> newLinkedList = new LinkedList<>();
        for (Object object : linkedList) {
            newLinkedList.add(0, object);
        }
        return newLinkedList;
    }
    

    相关文章

      网友评论

          本文标题:单链表反转

          本文链接:https://www.haomeiwen.com/subject/basvtktx.html