剑指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;
        }
    }
}
原文地址:https://www.cnblogs.com/ITxiaolei/p/13166912.html