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

    
    
    public class ListNode {
    
            int val;
            ListNode next;
            ListNode(int x){
                val = x;
            }
    
        public void setNext(ListNode next) {
                this.next = next;
    
        }
    }
    
    
    
    public class class_leetcode_反转一个链表 {
        public static ListNode reverseList(ListNode head){
            if(head==null||head.next == null){
                return head;
            }
            ListNode newHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
    
        public static ListNode reverseList2(ListNode head){
            if(head==null||head.next == null){
                return head;
            }
           ListNode newHead = null;
            while(head!=null){
                ListNode tmp = head.next;
                head.next = newHead;
                newHead = head;
                head = tmp;
            }
            return newHead;
        }
    
    
    
    
        public static void main(String[] args) {
            ListNode head = new ListNode(1);
            ListNode p1 = new ListNode(2);
            ListNode p2 = new ListNode(3);
            ListNode p3 = new ListNode(4);
            ListNode p4 = new ListNode(5);
            head.setNext(p1);
            p1.setNext(p2);
            p2.setNext(p3);
            p3.setNext(p4);
    
            ListNode aa = head;
            while(head.next!=null)
            {
                System.out.println(head.val);
                head = head.next;
            }
            System.out.println(head.val);
    
            ListNode A = reverseList2(aa);
            while(A.next!=null)
            {
                System.out.println(A.val);
                A = A.next;
            }
            System.out.println(A.val);
    
    
    
        }
    
    }
  • 相关阅读:
    如何完成看似不可能完成的任务
    SQL Server 2008 数据挖掘算法
    混在北京
    09年的一个方案,很遗憾没有采纳,回头看看,我还认为我是对的
    Metro Home
    InputScope
    Mozart Update 3 (7392…)
    搏斗Mango beta…
    Mango 7712 is coming
    HD2 update NODO
  • 原文地址:https://www.cnblogs.com/Knight66666/p/12765290.html
Copyright © 2011-2022 走看看