码迷,mamicode.com
首页 > 其他好文 > 详细

头插法反转链表

时间:2020-03-22 01:26:27      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:public   通过   eve   private   stat   vat   while   int   分析   

过程分析:

  1. 原链表 1->2->3
  2. 新建new节点,指向1,1指向null,此时head更新2
  3. head(2)插入new之后,1之前,此时head更新为3
  4. head(3)插入new之后,2之前

规律总结:

通过newList保存当前节点,通过下一次操作把新的节点插入二者之间实现反转。


class Test4 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3); // 1 -> 2 -> 3
        reverse(head);
    }

    public static ListNode reverse(ListNode head) {
        // core algorithm
        ListNode newList = new ListNode(-1);
        while (head != null) {
            ListNode next = head.next;
            head.next = newList.next;
            newList.next = head;
            head = next;

            // print the process
            ListNode print = newList;
            System.out.println("");
            while (null != print) {
                System.out.print(print.val + "->");
                print = print.next;
            }
            System.out.print("null");

        }
        return newList.next;
    }

    private static class ListNode {
        ListNode next = null;
        int val;

        ListNode(int val) {
            this.val = val;
        }
    }
}

输出结果:

技术图片

头插法反转链表

标签:public   通过   eve   private   stat   vat   while   int   分析   

原文地址:https://www.cnblogs.com/alyiacon/p/12543576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!