首页 > 其他 > 详细

leetcode-206-反转链表

时间:2019-08-03 00:24:59      阅读:71      评论:0      收藏:0      [点我收藏+]

问题:

技术分享图片

 

package com.example.demo;

public class Test206 {

    /**
     * 翻转链表
     * 方法一:迭代
     * 思路:
     * 每次循环的时候交换两个节点
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 构建一个新的链表
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            // 将当前处理节点的下一个节点暂存(也就是分开当前节点和下一个节点 2  3->4->5)
            ListNode next = cur.next;
            // 将当前节点赋给新链表 , 2->1
            cur.next = pre;
            // 重新覆盖新链表
            pre = cur;
            // 处理下一个节点
            cur = next;
        }
        return pre;
    }

    /**
     * 方法二:递归
     */
    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}

 

leetcode-206-反转链表

原文:https://www.cnblogs.com/nxzblogs/p/11276020.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!