zoukankan      html  css  js  c++  java
  • 【面试题】反转单链表

    面试题 反转单链表
    1、迭代法

    2、递归法

    Java 实现

    class ListNode {
        int val;
        ListNode next;
    
        ListNode(int val) {
            this.val = val;
            next = null;
        }
    
        @Override
        public String toString() {
            return val + "->" + next;
        }
    }
    
    public class ReverseListedList {
        public static void main(String[] args) {
            ListNode head = new ListNode(1);
            ListNode a = new ListNode(2);
            ListNode b = new ListNode(3);
            ListNode c = new ListNode(4);
            ListNode d = new ListNode(5);
            head.next = a;
            a.next = b;
            b.next = c;
            c.next = d;
    
            System.out.println("链表反转前:" + head);
            head = reverseListByIterative(head);
            System.out.println("迭代反转后:" + head);
    
            head = reverseListByRecursive(head);
            System.out.println("递归反转后:" + head);
        }
    
        public static ListNode reverseListByIterative(ListNode head) {
            if (head == null)
                return head;
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode prev = dummy.next;
            ListNode pcur = prev.next;
            while (pcur != null) {
                prev.next = pcur.next;
                pcur.next = dummy.next;
                dummy.next = pcur;
                pcur = prev.next;
            }
            return dummy.next;
        }
    
        public static ListNode reverseListByRecursive(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = reverseListByRecursive(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
    }
    

    运行结果

    链表反转前:1->2->3->4->5->null
    迭代反转后:5->4->3->2->1->null
    递归反转后:1->2->3->4->5->null
    
  • 相关阅读:
    ural 1723 Sandro's Book
    ural 1104 Don’t Ask Woman about Her Age
    ural 1052 Rabbit Hunt
    ural 1837 Isenbaev's Number
    ural 1348 Goat in the Garden 2
    ural 1207 Median on the Plane
    ural 1640 Circle of Winter
    段错误 核心已转储尝试解决
    显卡相关命令介绍【转载】
    Linux的top命令学习【转载】
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10585879.html
Copyright © 2011-2022 走看看