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

     1 package com.algorithm;
     2 
     3 //输入一个链表,反转链表后,输出链表的所有元素。
     4 public class ReverseListMe {
     5     
     6     public ListNode ReverseList(ListNode head) {
     7         //运行时间:36ms 占用内存:528k
     8         if(head == null) {
     9             return head;
    10         }
    11         if(head.next == null) {
    12             System.out.println(head.val);
    13             return head;
    14         }
    15          ListNode front = head;//前一个
    16          ListNode back = head.next;//后一个
    17          ListNode guard = back.next;//第三个
    18          front.next = null;//将最后一个赋值为null
    19          while(back != null) {
    20              back.next = front;//把第二项的next 赋值为front
    21              front = back;
    22              back = guard;//将guard 赋值给front
    23              if(guard != null)
    24               guard = guard.next;//将guade的next赋值给guard
    25          }
    26          head = front;
    27          while(front != null) {
    28              System.out.println(front.val);
    29              front = front.next;
    30          }
    31          return head;
    32     }
    33     public static void main(String[] args) {
    34          ListNode la = new ListNode(1);
    35           ListNode lb = new ListNode(2);
    36           ListNode lc = new ListNode(3);
    37           la.next = lb;
    38           lb.next = lc;
    39           lc.next = null;
    40           new ReverseListMe().ReverseList(la);
    41     }
    42     /*class ListNode {
    43         int val;
    44         ListNode next = null;
    45         ListNode(int val) {
    46             this.val = val;
    47         }
    48     }*/
    49 }
    1 ListNode pre = null;   
    2 ListNode next = null;    
    3 while (head != null) {        
    4     next = head.next;        
    5     head.next = pre;        
    6     pre = head;        
    7     head = next;    
    8 }    
    9     return pre;
  • 相关阅读:
    IP地址
    ACL访问控制列表
    DHCP原理及配置
    VRRP原理及配置
    ASP.NET CORE RAZOR :向 Razor 页面应用添加模型
    HBuilder + PHP开发环境配置
    添加相关功能
    基于stm32的水质监测系统项目基础部分详细记录
    表单数据验证方法(二)——ASP.NET后台验证
    表单数据验证方法(一)—— 使用validate.js实现表单数据验证
  • 原文地址:https://www.cnblogs.com/fankongkong/p/6517989.html
Copyright © 2011-2022 走看看