zoukankan      html  css  js  c++  java
  • 反转链表

    遍历法:

    public class ReverseListNode {

        public ListNode Reverse(ListNode root){

            ListNode Cur = root;

            ListNode Pre = null;

            ListNode headNode =null;

            while (Cur!=null){

                ListNode next=Cur.next;

                if(next==null)

                    headNode = Cur;

                Cur.next = Pre;

                Pre = Cur;

                Cur = next;

            }

            return headNode ;

        }

     

        public static void main(String[] args) {

            ListNode root=new ListNode(1);

            root.next=new ListNode(2);

            ListNode R=new ReverseListNode().Reverse(root);

        }

    }

    class ListNode {

     

        public int val;

        public ListNode next;

     

        public ListNode(int x) {

            val = x;

        }

    }

    递归实现:

    package TEST.反转链表;
    
    /**
     * Created by nick on 2018/10/9.
     */
    public class reverseLinkedList {
        static ListNode reverseLinkedList(ListNode node) {
            if (node == null || node.next == null) {
                return node;
            } else {
                ListNode headNode = reverseLinkedList(node.next);
                node.next.next = node;//headNode和node是两个相交的链表
                node.next = null;
                return headNode;
            }
        }
    
        public static void main(String[] args) {
            ListNode root=new ListNode(1);
            root.next=new ListNode(2);
            root.next.next=new ListNode(3);
            ListNode R=reverseLinkedList(root);
        }
    
    }

  • 相关阅读:
    Python基础教程【读书笔记】
    Python基础教程【读书笔记】
    Python基础教程【读书笔记】
    Python基础教程【读书笔记】
    JS实现焦点图轮播效果
    JQuery+CSS3实现Ajax加载时loading效果
    JQuery实现锚点平滑滚动
    CSS3之嵌入Web字体
    HTML5本地存储
    impress.js初体验——前端装X利器
  • 原文地址:https://www.cnblogs.com/nickup/p/9761133.html
Copyright © 2011-2022 走看看