zoukankan      html  css  js  c++  java
  • Single List Reversion

    LeetCode

    1. 基于头插法的迭代:

     1 public ListNode reverseList(ListNode head) {
     2         if(head == null) return null;
     3         ListNode res = new ListNode(0);
     4         res.next = head;
     5         ListNode cur = head;
     6         while(cur.next != null){
     7             ListNode tmp = cur.next;
     8             cur.next = tmp.next;
     9             tmp.next = res.next;
    10             res.next = tmp;
    11         }
    12         return res.next;
    13 }

    2. 就地逆置的简洁迭代(elegant)

     1 public ListNode reverse(ListNode head){
     2         ListNode prev = null;
     3         while(head != null){
     4             ListNode next = head.next;
     5             head.next = prev;
     6             prev = head;
     7             head = next;
     8         }
     9         return prev;
    10     }

    3. 递归

    1 ListNode* reverseList(ListNode* head) {
    2         if (!head || !(head -> next)) return head;
    3         ListNode* node = reverseList(head -> next);
    4         head -> next -> next = head;
    5         head -> next = NULL;
    6         return node; 
    7 }
  • 相关阅读:
    JS小功能系列9商品筛选
    JS小功能系列8省市联动
    if u
    js属性
    js初识
    弹性盒
    项目合作
    css重置
    关于响应式布局
    自我定位
  • 原文地址:https://www.cnblogs.com/niuxichuan/p/7359741.html
Copyright © 2011-2022 走看看