• 链表模板总结


    单链表:

    public class ListNode {
      int val;
      ListNode next;
      ListNode (int val) {
        this.val = val;
      }
    }

    1、反转单链表

    迭代:

    方法1:

    public ListNode reverseList(ListNode head) {
        if (head == null) {
             return null; 
        }
    
        ListNode preH = new ListNode(0);
        preH.next = head;
        ListNode preCur = head;
        ListNode cur = preCur.next;
    
        while (Cur != null) {
            preCur.next = Cur.next;
            Cur.next = preH.next;
            preH.next = Cur;
            Cur = preCur.next;
        }
    
        return preH.next;
    }
    View Code

    方法2:

    public class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode pre = null;
            while (head != null) {
                ListNode next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            return pre;
        }
    }
    View Code

    递归:

    public class Solution {
        public ListNode reverseList(ListNode head) {
            //ListNode pre = null;
            return reverseNode(head, null);
        }
        
        private ListNode reverseNode (ListNode head, ListNode pre) {
            if (head == null) {
                return pre;
            }
            ListNode next = head.next;
            head.next = pre;
            //pre = head;
            return reverseNode(next, head);
        }
    }
    View Code

    2、寻找单链表的中点

    public ListNode findMid(ListNode head) {
      ListNode slow = head;
      ListNode fast = head;
      while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
      }
      return slow;
    }
    View Code
    不要让执行的勤奋掩盖思考的懒惰!
  • 相关阅读:
    CUDA 纹理内存
    CUDA三维数组
    cutil.h问题
    GPU和CPU耗时统计方法
    NVIDIA CUDA Library Documentation
    device not ready cuda
    送给女朋友的礼物
    手机屏幕录制软件分享
    统计函数运行时间-CPU端
    二十四孝,图文并茂,古今必读!
  • 原文地址:https://www.cnblogs.com/zhiyangjava/p/6523481.html
Copyright © 2020-2023  润新知