zoukankan      html  css  js  c++  java
  • 剑指offer:面试题16、反转链表

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。

    代码示例

    public class Offer16 {
        public static void main(String[] args) {
            //构建链表
            ListNode head = new ListNode(1);
            head.next = new ListNode(2);
            head.next.next = new ListNode(3);
            head.next.next.next = new ListNode(4);
            Offer16 testObj = new Offer16();
            testObj.printList(head);
            ListNode res = testObj.reverseList(head);
    //        ListNode res = testObj.reverseList2(head);
            testObj.printList(res);
        }
        //法1:递归
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode next = head.next;
            head.next = null;
            ListNode newHead = reverseList(next);
            next.next = head;
            return newHead;
        }
    
        //法2:头插法
        public ListNode reverseList2(ListNode head) {
            ListNode newList = new ListNode(-1);//建立哑节点
            while (head != null) {
                ListNode next = head.next;
                head.next = newList.next;//将新遍历到的节点指向新链表的第一个结点
                newList.next = head;//哑节点指向新插入的节点
                head = next;//继续遍历原链表
            }
            return newList.next;
        }
        //打印链表
        public void printList(ListNode head) {
            if (head == null) {
                return;
            }
            while (head != null) {
                System.out.println(head.val);
                head = head.next;
            }
            System.out.println();
        }
        //定义节点
        static class ListNode {
            int val;
            ListNode next;
            ListNode(int val) {
                this.val = val;
            }
        }
    }
    
  • 相关阅读:
    python的ORM框架SQLAlchemy
    SQLAlchemy技术文档(中文版)-下
    SQLAlchemy技术文档(中文版)-上
    python的class的__str__和__repr__(转)
    虚拟化技术之KVM
    cobbler部署安装
    pxe+kickstart 无人值守安装CentOS7.1
    超详细saltstack安装部署及应用
    页面缓存
    db2 常用命令
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13166912.html
Copyright © 2011-2022 走看看